下面的代码遇到一些问题...有什么问题吗?
我无法使用 xstrcpy 进行复制和打印,当我尝试在 main 中打印整个字符串时,它会打印一个空行,尽管在 while 循环中会打印每个字符...但不会打印紧邻 while 循环下面的字符串...Don不知道为什么会发生这种情况:(
代码:
#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
I cannot use the xstrcpy to copy and print and it prints a blank line when i try to print the whole string in main though in the while loop each character is printed...but not the string immediately below the while loop...Don't know why this is happening:(
Code:
#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;
}
Output:
11
Hello World
Hello Again
H
e
l
l
o
A
g
a
i
n
ׁׁ
Exited: ExitFailure 4
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您在复制字符串时更改了 ptr1 的指针地址。因此,当您打印出 ptr1 时,它实际上指向字符串的末尾,这是一些垃圾值。
所以你需要做的是将 ptr1 保留在 xstrcpy 的开头并返回该起始地址,我认为这将正确打印出 ptr1 。
You have changed the pointer address of ptr1 as you copied the string. So by the time you print out ptr1, it is actually pointing to the end of the string which is some garbage value.
So what you need to do is to keep the ptr1 in the beginning of xstrcpy and return that start address and that will correctly print out the ptr1, I think.