Yahoo Answers is shutting down on May 4th, 2021 (Eastern Time) and beginning April 20th, 2021 (Eastern Time) the Yahoo Answers website will be in read-only mode. There will be no changes to other Yahoo properties or services, or your Yahoo account. You can find more information about the Yahoo Answers shutdown and how to download your data on this help page.
Trending News
this c program for creating strcat() using pointers is printing only 'hello'. plz help. code is given as answer and screenshot.?

3 Answers
- ?Lv 73 years agoFavorite Answer
for(i=0;(*(s+y)=*(t+i))!='\0';i++) // y is not increasing
change it to
while(*(y+s++)=*t++);
you are working way too hard
this is easier:
#include <stdio.h>
char * mystrcat(char * s1, char * s2){
char * s;
s=s1;
while(*s1) s1++;
while(*s1++ = * s2++);
return s;
}
int main(void){
char s[100]="testing";
char s2[100]="add this";
printf("%s\n",mystrcat(s,s2));
return 0;
}
- husoskiLv 73 years ago
The problem seems to be coding *(s+y) instead of *(s+y+i) in the middle expression of your for statement. You're storing every copied character to the same place.
By the way, you can use array syntax with pointers in C. In fact, array syntax is formally defined in terms of pointers.
The operation a[b] is formally defined to be *((a) + (b)), so s[y+i] = t[i] gets the same assignment operation done as your *(s+y+i) = *(t+i) and is easier to read.
Either way, you are using pointer arithmetic inside the loop, and that's probably not what the "strcat with pointers" assignment is trying to teach you. Consider a loop that looks more like:
char *from = t; /* source pointer */
char *to = s + strlen(s); /* destination pointer*/
while (*from != 0) { *to++ = *from++; }
*to = '\0'; /* store the terminating zero byte */
/* OOPS ... the above used to read *from = '\0'; */
Now the only pointer operations in the loop are incrementing pointers. That's roughly two integer additions instead of 4 (two in s+y+i, one in t+i, and one in i++).
A note on your code: That will copy the zero terminating byte from string t during that for loop, so you don't need that extra code to store another '\0' after the loop. That's an "edge case" problem for some later use of the function, where the extra stored 0 byte could overrun an allocated array that was just large enough to hold the concatenated result.
- 3 years ago
//code in question
#include<stdio.h>
#include<string.h>
int strcats(char *, char *);
int main()
{
char p[100]={"hello"},q[]={"world"};
strcats(p,q);
printf("%s",p);
return 0;
}
int strcats(char *s,char *t)
{
int i,y;
y=strlen(s);
for(i=0;(*(s+y)=*(t+i))!='\0';i++)
;
y=strlen(s);
*(s+y)='\0';
return 0;
}



