c - 在c中复制字符串时出现段错误

标签 c segmentation-fault

以下代码显示段错误。如何解决问题?代码有什么问题?

#include <stdio.h>

void stcp (char *, char *);

int
main ()
{
  char *s = "This is first string";
  char *t = "string to be copied";
  stcp (s, t);
  printf ("%s", s);
  getch ();
}

void
stcp (char *s, char *t)
{
  while ((*s++ = *t++) != '\0');

}

最佳答案

默认情况下,字符串文字是const。要使其成为非 const,您必须将其设为数组:

char s[] = "this is my string";
char t[] = "another string";

关于c - 在c中复制字符串时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10769524/

相关文章:

c - 链接列表无法正常工作

C++段错误(核心转储)和使用结构

c - 尝试访问二进制文件时出现段错误

token 方法的 C 段故障 : Possible malloc error?

c++ - 获取 C++ 段错误

c - 如何使用 pthread_cancel 避免内存泄漏?

c - 迭代 GList 的宏

c - 在 Unix/Solaris 中验证用户名

c - 仅给出成员位置时结构的位置

python - 在 .so 文件中使用 C 模块时出现段错误