Morfeo Rejocktana Morfeo Rejocktana - 7 months ago 43
C Question

how to assign char array to another char array with another size in C

I want to assign an array to another array. Both arrays do not have the same size:

char array1[7] = "abcdefg";
char array2[3];

How can i assign three(3) values from array1 into array 2? I tried so:

array2[3] = {array1[2], array1[3], array1[4]};

and i´d become the following error message:

expected expression before ´{´token

I know that i can use (
) when the arrays have the same size.

I have more experience with VHDL and verilog. In VHDL it could look like this:

array2 := arry1(2 upto 4);

But i do not have much experience with C programing.

Thank you


If you wish to do the copy at run-time, you can either use memcpy():

memcpy(array2, array1 + 2, 3);

or just write your own copy loop:

for (int i = 0; i < 3; i++) array2[i] = array1[i + 2];

Note that, depending on the surrounding code and your C compiler and optimization settings, these two methods may or may not end up compiling into the same binary. Specifically, it's quite possible for an optimizing compiler to both inline memcpy() and to transform the explicit copy loop into a call to memcpy(), depending on what the compiler thinks would be most efficient.

Also note that, if the arrays were of some type other than char, the length argument to memcpy() would need to be multiplied by the size of the element type in bytes. However, the C standard guarantees that sizeof(char) == 1.