【发布时间】:2018-01-31 15:56:48
【问题描述】:
我正在为“二分搜索”编写代码。与此同时,我写了一些代码来查看我的起点、中间点和终点在哪里。为此,我打印了一个字符串,其中开始、中间和结束的数字用方括号括起来。因为这导致我出现分段错误,所以我复制了代码并将其压缩为导致问题的最少代码量。
这是代码:
#include <stdio.h>
#include <string.h>
int main(void)
{
int values[9] = {1, 3, 6, 9, 10, 14, 16, 17, 21};
int n = sizeof(values) / sizeof(int); // <-- make this is a "const", and the "segmentation fault" goes away
char buf[20] = "";
char num[6] = "";
for(int i = 0; i < n; i++)
{
printf("i: %i, n: %i\n", i, n);
sprintf(num, "[%i] ", values[i]);
strcat(buf, num);
}
return 0;
}
用这一行编译:
clang -std=c99 -Wall -Werror loop.c -o loop
不知何故,“n”被改变了,尽管它不应该被改变。至少不是我改的。
那么为什么会这样呢?
【问题讨论】:
-
顺便说一句,不要亲自投票。我没有投票,但我想选民投票是因为这个问题对其他人没有太大用处——这可能不是他们在查找自己的问题时要寻找的东西。您在将问题简化为可重现的示例方面做得很好。