【发布时间】:2015-03-23 10:29:05
【问题描述】:
我想前段时间我尝试了以下代码,一切都很顺利。 但是现在,我有一个分段错误,我无法找出哪个部分提供了它。
#include <stdio.h>
#include <stdlib.h>
int main() {
char *test = NULL; // Empty string
char *a = "programming test";
int i = 0;
/* While the string "a" does not encounter a space,
I put its characters in the empty string "test" one by one. */
while(a[i] != ' ') {
test[i] = a[i];
i++;
}
printf("%s\n", test);
return 0;
}
这个小代码对我来说似乎是正确的,我无法确定哪里出了问题。
【问题讨论】:
-
您正在取消引用并写入
NULL指针(带有一些偏移量)。那只会出错。在写入测试之前分配内存并将test指向它。
标签: c arrays pointers segmentation-fault c-strings