1

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;
 }
  • 3
    `result[strlen(result)]='@';` will delete the 0-terminator of the string. Did you try `strcat`? – mch Jan 09 '17 at 10:28
  • 1
    It also depends on what `server` is and whether you are overflowing the buffer `result`. – P.P Jan 09 '17 at 10:30
  • 4
    `snprintf(result, sizeof result, "%s@%s", message, server);`, also `char mail[150];` --> `char server[150];` – BLUEPIXY Jan 09 '17 at 10:31

1 Answers1

4

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.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
  • Yes, definitely use `snprintf(result, sizeof result, "%s@%s", message, server);`. Also consider better names for the variables, they don't match the prompts very well. – unwind Jan 09 '17 at 10:38