2
Usually when we want to copy the contents of a particular string into another string we can use the functions strncat
or strncpy
.
Using strncat
The use of strncat to copy strings is kind of "wrong" as this function serves to concaterate/join strings and not copy, but still is possible and for that just use the function memset in string and then apply the function strncat
thus preventing the target string from receiving garbage. Follow the code below for a larger view of the thing:
#include <stdio.h>
#include <string.h>
int main(void){
char foo[15];
printf("\nFoo (lixo): %s\n", foo);
memset(foo, 0, 15);
strncat(foo, "BOING 737", 10);
printf("\nFoo: %s\n", foo);
return 0;
}
Using strncpy
#include <stdio.h>
#include <string.h>
int main(void){
char foo[15];
printf("\nFoo (lixo): %s\n", foo);
strncpy(foo, "BOING 737", 10);
printf("\nFoo: %s\n", foo);
return 0;
}
Now comes the question: It would be necessary, for precautionary reasons in order to avoid garbage, to use memset
before strncpy
?