Reputation: 121
Anyone know how to copy to strings? Cause I used the function strcpy but when I print the result it show strange characters. I want to concatenate 'name' + '@' + 'e-mail'. With scanf I have to put the character null '\0'?
#include <stdio.h>
#include <string.h>
int main (){
char message[150];
char name[150];
char mail[150];
char result[150];
printf("Introduce name: \n");
scanf("%s",message);
printf("Introduce email \n");
scanf("%s",server);
strcpy(result,message);
result[strlen(result)]='@';
strcpy(&result[strlen(result)],server);
printf("RESULT: %s\n",result);
return 0;
}
Upvotes: 1
Views: 95
Reputation: 234785
result[strlen(result)]='@';
overwrites the NUL terminator introduced into result
by strcpy(result,message);
. So the result of a subsequent strlen
is undefined.
A better solution is to use strncat
, or you could get away with writing
char result[150] = {'\0'};
which will initialise the entire array.
But you still run the risk of overflowing your result
array. You could use the safer strncpy
to obviate that. Better still, use snprintf
and have the C standard library perform the concatenation for you.
Upvotes: 4