c中复制字符串的分段错误

时间:2012-05-26 20:27:24

标签: 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');

}

2 个答案:

答案 0 :(得分:1)

默认情况下,字符串文字为const。要使它成为un-const,你必须使它成为一个数组:

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

答案 1 :(得分:0)

#include <stdio.h>

void stcp (char *s, char *t);

int main (void)
{
  int i;
  char s[] = "This is first string";
  char t[] = "string to be copied        ";
  stcp (s, t);
  printf ("%s\n", s);
  printf ("%s\n", t);
  //getch ();
  return 0;
}

void stcp (char *s, char *t)
{
  int i;
  for (i=0;  (s[i]  != '\0')  &&  (t[i] != '\0') ;i++) {
    printf("%c  %c\n",s[i],t[i]);
    s[i] = t[i];
  }
  s[i] ='\0';
}