I am going through some exercises and am trying to concatenate two strings using only pointers (no char arrays).
My code seems to compile(Note: I am using the old 16-bit Open Watcom compiler):
#include <stdio.h>
int main(){
char *str1 = "first";
char *str2 =" second";
strcat2(str1,str2);
for(;*str1!='\0';str1++){
printf(str1);
}
return 0;
}
int strcat2(char *s,char *t){
for(;*s!='\0';s++){
;
}
while((*s++ = *t++)!='\0'){
;
}
*t++;
t='\0';
return 0;
}
When I tried to run it nothing happens.
I am sure my above work is horribly flawed. Any advice and help will be much appreciated.
the
str1andstr2you have declared are string literals, which cannot be modified. In linux executables the contents of the address which thestr1andstr2points to are stored in.rodatasection of the executable which is not writeable. In other executables the contents are stored in a similar location which is not writeable. You should use an array or dynamically allocated memory area to do this work. Make sure when concatenating the string to which you are pasting the other string has enough space to hold both of them.EDIT1:
Either do
or