我想前段时间我尝试了以下代码并且一切顺利。 但是现在,我有一个段错误,我无法找出它是由哪个部分提供的。
#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;
}
这个小代码对我来说似乎是正确的,我无法确定哪里出了问题。
最佳答案
你没有在这里分配内存:
char *test = NULL; // Empty string
给它一些内存:
char *test = malloc(sizeof(char) * 50);
在循环 nul
之后终止它:
while(a[i] != ' ') {
test[i] = a[i];
i++;
}
test[i] = '\0';
printf("%s\n", test);
关于c - 不明白为什么会出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29207936/