Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copying structure elements vs copying array elements in C

As described in the answer to this question Copying one structure to another, We can copy the contents of a structure element to another by simple assignment. e1=e2;

But this simple assignment does not work when copying array elements. Can someone offer an explanation?

Thanks.

like image 668
sheetal_158 Avatar asked Dec 06 '25 08:12

sheetal_158


2 Answers

Arrays are second-class citizens in C: you cannot assign an array to an array and you cannot return an array from a function.

Chris Torek offers this explanation in comp.lang.c:

"Note that V6 C also did not support struct-valued arguments and struct-valued return values. One might, then, imagine that Dennis figured that any return value that did not fit in a register was too much work to put into the compiler at that point."

like image 65
ouah Avatar answered Dec 08 '25 06:12

ouah


Array is not a modifiable lvalue ("something that has a location (in memory)"). This means that although it is a lvalue, it can't be a left operand of assignment operator =.

In case of structure, other than assignment*, C provides no operations on entire structures. One can't use ==, != operators to test whether two structures are equal or not.

You can create dummy structures to enclose arrays that will be copied later:

struct
{
    int arr[5];
} arr1, arr2;

Latter you can assign

arr1 = arr2;  

*The = operator can be used only with compatible structure types.

like image 28
haccks Avatar answered Dec 08 '25 04:12

haccks



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!