user2131316 user2131316 - 1 month ago 15
C Question

how to copy char array to another char array in C?

In C, I have two char arrays:

char array1[18] = "abcdefg";
char array2[18];


How to copy the value of
array1
to
array2
? Can I just do this:
array2 = array1
?

Answer

You can't directly do array1 = array2. Because in this case you would manipulate the addresses (char *) of the arrays and not their values.

For this kind of situation, it is recommended to use strncpy to avoid a buffer overflow, especially if array1 is filled from user input (keyboard, network, etc.). Like so:

// Will copy 18 characters from array1 to array2
strncpy(array2, array1, 18);

As @Prof. Falken mentioned in a comment, strncpy can be evil. Make sure your target buffer is big enough to contain the source buffer (including the \0 at the end of the string).