Normally when we want to copy the contents of a given string into another string we can use the strncat
or strncpy
functions.
Using strncat
The use of strncat to copy strings is kind of "wrong", as this function is used to concatenate / join strings and not copy, but it is still possible for this you just have to use the memset function in string and then apply the strncat
function thus preventing the destination string from receiving garbage. Here is the code below for a closer look at 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: Would it be necessary, for precautionary reasons to avoid junk, to use memset
before strncpy
?