本文介绍了错误使用时写的strcat()指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想学会与下用K&放C编程语言; R 。我想写使用指针并且在的strcat()程序。
I am trying to learn C with The C programming Language by K&R. I am trying to write a the strcat() program using pointers.
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; }但是我收到输出中为
But I am getting the ouput as
stack overflow Segmentation fault为什么不工作?任何人都可以在这里澄清错误。
Why is it not working ? Can anybody clarify the mistake here..
推荐答案由于该指针指向文字,不仅是那些只读的目标不够大,可以包含字符串。至少对于字符串1 你想使用足够至少大大小的数组包含两个字符串(包括终止)。这样的:
Because the pointers are pointers to literals, and not only are those read only the destination is not big enough to contain both the strings. For at least string1 you would want to use an array of at least big enough size to contain both strings (including the terminator). Like:
char string1[128] = "Stack";或
char string1[128]; strcpy(string1, "Stack");更多推荐
错误使用时写的strcat()指针
发布评论