Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to copy a char array in C?

Tags:

arrays

c

char

copy

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?

like image 926
user2131316 Avatar asked May 20 '13 08:05

user2131316


People also ask

How do you copy a character array?

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.

Can array be copied in C?

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.

How do I make a copy of a character?

char linkCopy[sizeof(link)] = strncpy(linkCopy, link, sizeof(link));

How do I copy a char pointer?

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 .


1 Answers

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).

like image 66
aymericbeaumet Avatar answered Sep 28 '22 05:09

aymericbeaumet