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
at the end of the string).
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…