为什么我在这个字符串复制程序中遇到分段错误?

时间:2013-05-23 02:44:12

标签: c string pointers

我用指针编写了一个字符串复制程序,但它有一个分段错误,不知道为什么。

由于

这是我的代码:

#include<stdio.h>

void strcp(char *s,char *t){
   while(*s++=*t++)
        ;
     }

void main(){
  char *d="this is destination";    
  char *s="this is source";  
  strcp(d,s);
  while(d++){
     printf("%s  " ,*d);
   }

    return;
  }

2 个答案:

答案 0 :(得分:1)

d指向字符串文字,写入字符串文字是未定义的行为。您也可以按如下方式定义d

char d[]="this is destination"; 

您还需要修复printf并从中循环:

while(d++){
  printf("%s  " ,*d);
}

到此:

printf("%s  " ,d);

你可以删除循环。最后,main应始终返回int

int main()

答案 1 :(得分:0)

即使你没有传入文字,如果t比s长,那么你的指针就会结束。