在以下带有 printf() 语句的代码中,我遇到了一个段错误:11。如果没有它,我不会收到任何错误,但我希望能够看到新字符串值中的正确值。我该怎么做?
char* newstring;
for(int i = 0; i < len; i++)
{
printf("value %d\n", tempfullstring[i]);
if (tempfullstring[i]>=97 && tempfullstring[i] <=122)
{
char value = tempfullstring[i];
newstring += value;
}
}
printf("The new string is %s", newstrng);
return 0;
最佳答案
我认为你对 C 字符串的工作原理有误解:
- 它们不会在声明时得到初始化(所以
char* newstring;
必须单独分配,否则你会得到未定义的行为) - 它们不能与
+=
运算符连接(因此newstring += value;
无效) - C 字符串的空间需要明确管理(所以你要么需要在自动存储区分配你的
newstring
,要么在末尾添加一个free
).
修复程序的最简单方法是猜测 newstring
的长度,然后使用 strcat
向其附加数据:
char newstring[1000]; // some max length
newstring[0] = '\0'; // make it an empty string
...
strcat(newstring, value); // instead of newstring += value
关于C Segmentation fault 错误打印,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14964246/