How to copy a char array in C?

user2131316 picture user2131316 · May 20, 2013 · Viewed 434.4k times · Source

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

aymericbeaumet picture aymericbeaumet · May 20, 2013

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

What you, conceptually, want is to do is iterate through all the chars of your source (array1) and copy them to the destination (array2). There are several ways to do this. For example you could write a simple for loop, or use memcpy.

That being said, the recommended way for strings is to use strncpy. It prevents common errors resulting in, for example, buffer overflows (which is especially dangerous 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).