Facing some problem with the following piece of code...Is there something wrong?
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);
print开发者_JS百科f("%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
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.
精彩评论