请使用 gcc 在您的机器上运行它,看看它是否也给您一个段错误输出。我认为程序没有任何问题。我是 C 的初学者。求助!!
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char *scat(char *,char *);
void main()
{
char *s="james";
char *t="bond";
char *w=scat(s,t);
printf("the con: %s\n", w);
free(w);
}
char *scat(char *s,char *t)
{
char *p=malloc(strlen(s)+strlen(t)+1);
int temp=0 , ptr=0;
while(s[temp]!='\0'){
p[ptr++]=s[temp++];
}
temp=0;
while(t[temp]='\0'){
p[ptr++]=t[temp++];
}
return p;
}
最佳答案
第二个循环没有效果:
while(t[temp]='\0') { // <<== Assignment!!!
p[ptr++]=t[temp++];
}
这应该是 !=
而不是 =
,或者更好的是,您可以完全删除零:
while(t[temp]) { // Zero-checking is implicit in C
p[ptr++] = t[temp++];
}
因为您不是在写入s
或t
,所以将它们都声明为const
可能是个好主意。这会在上面的 while
循环中捕获赋值。
关于使用指针的strcat的c程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14265940/