【发布时间】:2013-08-31 15:51:13
【问题描述】:
我正在尝试通过The C programming Language by K&R 学习 C。我正在尝试使用指针编写strcat() 程序。
char *strcat (char *s, char *t){
char *d;
d = s;
while(*s++);
s--;
while(*s++ = *t++);
return d;
}
int main () {
char *name1;
char *name2;
name1 = "stack" ;
name2 = "overflow";
printf("%s %s\n", name1, name2);
printf("strcat out : %s", strcat(name1, name2));
return 0;
}
但我得到的输出为
stack overflow
Segmentation fault
为什么它不起作用?任何人都可以在这里澄清错误..
【问题讨论】:
-
这是 C 还是 C++?为什么你有两个标签?
-
@Doorknob - 两种语言的答案都是一样的。
-
你需要学习数组和指针,声明你的
char name1[SIZE];和char name2[SIZE];并将赋值语句name1 = "stack";替换为strcpy(name1, "stack");,strcpy(name2, "overflow");
标签: c++ c arrays pointers kernighan-and-ritchie