I am reading K&R and trying to do the excercise involving writing a version of strcat (attach one string to the end of the other) using pointers. This is what I have:
#include<stdio.h>
void mystrcat(char *s,char *t)
{
while(*s++);
*s--;
while(*s++ = *t++);
}
int main()
{
int size = 1024;
char *s1, *s2;
s1 = malloc(size);
s2 = malloc(size);
s1 = "Hello ";
s2 = "World";
mystrcat(s1,s2);
printf("%s",s1);
return 0;
}
The program runs but crashes straight away, not very experienced with pointers so can't work out the error.
s--instead of*s--.mallocthere already? Which exercise is it? Should be pointer chapter...malloc()to assure the operation was successful. Then pass those pointers tofree()before exiting the program.s1 = "Hello ";. This overlays the pointer returned from malloc with the ptr to "Hello ", thereby forever losing the original pointer, resulting in a memory leak. Suggest:char * ptr = "Hello "; for( int i=0; *ptr[i]; i++ ) { s1[i] = ptr[i]; } s1[i] = '\0'; There is no need to malloc the s2, as that array will not be changing. Instead say:s2 = "World";while(*s++); *s--;with:for( ; *s; s++ );then no need for corrections to the 's' pointer