C Segmentation fault 错误打印

标签 c string printf fault

在以下带有 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/

相关文章:

c - 如何在 C 中打开文件以读取和写入其他文件?

c - 发送结构数组到函数

Java拆分方法

c - 用递归反转c中的字符串

c - 在不知道文件大小且数据类型顺序不一致的情况下如何从文件中读取数据

字符指针和 printf

c - increment , decrement , printf() 中的任务,为什么在 C 中以这种方式评估这些

c - scanf() 尝试输入带或不带空格的字符串时会关闭程序

c++ - 复制有关字节序的整数内容

c - ipv6 的 UDP 校验和验证 : how to fetch ipv6 source address from auxilliary data