gpt4 book ai didi

C编程strcat使用指针

转载 作者:行者123 更新时间:2023-12-02 05:33:45 24 4
gpt4 key购买 nike

我是 C 的初学者。我想使用指针来创建 strcat 函数。我做到了,但不知道它有什么问题。我使用了 gcc 编译器,它给出了段错误输出。

#include<stdio.h>
#include<string.h>

char scat(char *,char *);

void main()
{
char *s="james";
char *t="bond";

char *q=scat(s,t);
while(*q!='\0') printf("the concatenated string is %c",*q);
}

char *scat(char *s,char *t)
{
char *p=s;
while(*p!='\0'){
p++;
}
while(*t!='\0'){
*p=*t;
p++;
t++;
}
return p-s-t;
}

最佳答案

这个有效:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

char *scat(char *,char *); /* 1: your prototype was wrong */

void main()
{
char *s="james";
char *t="bond";

char *q=scat(s,t);
printf("cat: %s\n", q); /* 2: you can use %s to print a string */
free(q);
}

char *scat(char *s,char *t)
{
char *p=malloc(strlen(s)+strlen(t)+1); /* 3: you will have to reserve memory to hold the copy. */
int ptr =0, temp = 0; /* 4 initialise some helpers */

while(s[temp]!='\0'){ /* 5. use the temp to "walk" over string 1 */
p[ptr++] = s[temp++];
}
temp=0;
while(t[temp]!='\0'){ /* and string two */
p[ptr++]=t[temp++];
}
return p;
}

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

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