【问题标题】:C program segfault error [duplicate]C程序段错误[重复]
【发布时间】:2017-10-01 06:34:43
【问题描述】:

我希望输出是 XOllo,但我得到的是 segfault。

#include <stdio.h>
#include <string.h>

int main(){

  char *buf="hello";
  char *xys="XO";

  while(*buf != 'l'){
  *buf = *xys;
  xys++;
  buf++;
  }
  printf("%s \n", buf);
  return 0;
}

o/p-: 段错误

我需要 o/p 作为 XOllo,但我遇到了 seg 错误。请建议。

Please suggest. 

【问题讨论】:

  • 不应修改字符串文字。

标签: c


【解决方案1】:

变量bufxys 指向字符串文字,不能更改,因此尝试访问以重写导致SIGFAULT 的值,而不是您需要分配新变量并将值复制到其中:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(){

  char *buf="hello";
  char *xys="XO";
  char *tmp = (char *)malloc(strlen(buf));

  strcpy(tmp, xys);
  strcpy(tmp+2, buf+2);

  printf("%s \n", tmp);
  free(tmp);
  return 0;
}

如果需要查找l字符的准确位置,可以使用strchr函数获取其索引,方法如下:

int index = -1
const char *ptr = strchr(buff, 'l');
if(ptr) {
   index = ptr - values;
}

【讨论】:

  • 我只想指出您已经添加了一个新标题stdlib.h,OP 可能会错过它。同时你已经投射了malloc 的结果。如果她错过了标题,那可能会隐藏她会收到的警告,结果可能是灾难性的..
  • 是的,你是对的,感谢您的评论。
  • 不,要求是不使用库函数。
  • 感谢 Artem,在新代码中,我可以编辑字符串 buf 但与以前的情况不同
  • 你能不能打开一个新问题,因为现在它似乎是完全不同的问题,而且没有新库的附加要求:)?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-09-06
  • 2012-05-26
  • 2021-01-08
  • 1970-01-01
  • 1970-01-01
  • 2015-05-29
相关资源
最近更新 更多