gpt4 book ai didi

c - 面对以下代码的一些问题......有什么问题吗?

转载 作者:太空宇宙 更新时间:2023-11-04 01:40:43 24 4
gpt4 key购买 nike

我无法使用 xstrcpy 进行复制和打印,当我尝试在 main 中打印整个字符串时它会打印一个空行,尽管在 while 循环中每个字符都被打印了...但不是 while 循环正下方的字符串。 ..不知道为什么会这样:(

代码:

#include<stdio.h>
#include<stdlib.h>
int xstrlen(char *);
char * xstrcpy(char *,char *);
main()
{
char *expptr1="Hello World";
char *expptr2 = "Hello Again";
char *expptr3;
printf("%d\n",xstrlen(expptr1));
expptr3 = xstrcpy(expptr1,expptr2);
printf("%s\n",expptr3);
}

int xstrlen(char *ptr)
{
//printf("I am here\n");
int count = 0;
while(*ptr++!='\0')
count++;
return count;
}

char * xstrcpy(char *ptr1,char *ptr2)
{
int i=xstrlen(ptr2);
printf("%s\n",ptr1);
printf("%s\n",ptr2);
ptr1 =(char *)malloc(i);
//printf("i am here\n");
while(*ptr2 != '\0')
{
*ptr1 = *ptr2;
printf("%c\n",*ptr1);
ptr1++;
ptr2++;
}
printf("%s",ptr1);
return ptr1;
}

输出:

11
Hello World
Hello Again
H
e
l
l
o

A
g
a
i
n
ׁׁ

Exited: ExitFailure 4

最佳答案

您在复制字符串时更改了 ptr1 的指针地址。所以当你打印出 ptr1 时,它实际上指向了字符串的末尾,这是一些垃圾值。

所以您需要做的是将 ptr1 保留在 xstrcpy 的开头并返回该起始地址,我认为这将正确打印出 ptr1。

关于c - 面对以下代码的一些问题......有什么问题吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5968681/

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