I was making an strcat using pointers in C, however I encountered the following problem in my while loop.
This is my code which fails to add str2 (here t) to str1 (here s):
char *pstrcat(char *s,char *t)
{
char *start=s;
while(*s++)
;
while(*s++=*t++){
;
}
return start;
}
My main code was:
int main()
{
char s[35]=" hi nice to meet you ";
char t[]="ho";
printf("%s",pstrcat(s,t));
return 0;
}
Expectations:
I was expecting a output of hi nice to meet you ho but instead got hi nice to meet you.
However when I changed the while loop (first while loop of pstrcat) a little bit it started to work.
The new while loop looked like:
while(*s!='\0')
s++;
Problem in brief:
I was unable to understand the difference of the two loops. I think both of them should work since both of them must be ending at '\0' with address of s currently pointing to '\0'.
However I must be wrong if my code isn't working.
There are two problems with the code.
pstrcatmoves the pointer beyond\0It can be rewritten as