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
?
Use the memcpy Function to Copy a Char Array in C char arrays are probably the most common data structure manipulated in the C code, and copying the array contents is one of the core operations for it.
1. C program to copy all elements of one array into another array. In this program, we need to copy all the elements of one array into another. This can be accomplished by looping through the first array and store the elements of the first array into the second array at the corresponding position.
char linkCopy[sizeof(link)] = strncpy(linkCopy, link, sizeof(link));
Syntax: char* strcpy (char* destination, const char* source); The strcpy() function is used to copy strings. It copies string pointed to by source into the destination . This function accepts two arguments of type pointer to char or array of characters and returns a pointer to the first string i.e destination .
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With