【发布时间】:2016-05-13 14:36:15
【问题描述】:
我正在解决 CS50 的问题,我必须根据用户输入的高度从# 中创建一个金字塔。这是我到目前为止所拥有的,但是对于 8 的高度,它只迭代一次。对于 7 的高度,我得到了大约四行只是乱七八糟的 #'s。
//Create GetPosInt() function
int GetPosInt(void) {
int n = GetInt();
while (n <= 0) {
printf("That won't work...\nRetry: ");
n = GetInt();
}
return n;
}
int main(void) {
printf("How high should Mario's pyramid be?\nHeight: ");
int h = GetPosInt();
while (h > 23) {
printf("Try something smaller!\nHeight: ");
h = GetPosInt();
}
char str[] = "##";
char strad[] = "#";
int l = h + 1;
for (int i = 0; i < h; i++) {
printf("%*s\n", l, str);
strcat(str, strad);
return 0;
}
}
这是我第一次尝试使用 string.h 库。
请仅提供有关修复我的代码的提示-我确定还有其他方法可以解决,但是如果可以这样,我想在课堂上保留它!
【问题讨论】:
-
看看循环里面的代码……你不做点什么把它里面结束吗?我想你会的。
-
char str[] = "##";: 不存在可以连接字符串的额外空间。 -
创建数组
str以包含三个 字符:两个'#'字符和字符串终止符。附加到 this 会写出 out of bounds 并给你 undefined behavior。 -
@AnishSharma 嗯,我很喜欢轻松获胜... ;)
-
@AnishSharma 好吧,正如 Joachim 所写:这是未定义的行为。