gpt4 book ai didi

使用指针的strcat的c程​​序

转载 作者:太空宇宙 更新时间:2023-11-04 02:59:00 25 4
gpt4 key购买 nike

请使用 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++];
}

因为您不是在写入st,所以将它们都声明为const 可能是个好主意。这会在上面的 while 循环中捕获赋值。

关于使用指针的strcat的c程​​序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14265940/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com