Copying structure elements and 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 a simple assignment. e1 = e2;

But this simple assignment doesn't work when copying array elements. Can anyone suggest an explanation?

Thank.

+3


source to share


3 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 does not support structured arguments and structured return values. Then perhaps imagine Dennis realized that any return value that didnโ€™t fit into case was too much work for the compiler at this point."

+1


source


An array is not a mutable lvalue ( "what is the case (in memory)" ). This means that although it is an lvalue, it cannot be the left operand of an assignment operator =

.

In the case of a structure other than an assignment, * C does not perform operations on entire structures. You can not use the operators ==

, !=

to check whether the two structures are equal or not.

You can create dummy structures to add arrays to be copied later:

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

      



The latter you can assign

arr1 = arr2;  

      


* The operator =

can only be used with compatible structure types.

+1


source


The array name is an alias for the address of the first element of the array *:

#include <stdio.h>

int main()
{
    int foo[5] = {2, 3, 4, 5, 6};
    int *bar = foo; 
    // now bar == foo, i.e. bar == &foo[0], so changing bar[2] changes foo[2]
    // bar[2] works because of pointer arithmetic

    printf("    foo is: %p\n",foo);     // prints the address of the first element of foo
    printf("&foo[0] is: %p\n", &foo[0]); // also prints the address of the first element of foo
    printf("    bar is: %p\n", bar);
    printf("&bar[0] is: %p\n", &bar[0]);
    printf(" foo[2] is: %d\n", foo[3]);
    printf(" bar[2] is: %d\n", bar[3]);

    return 0;

}

      

* with some exceptions. Namely sizeof foo != &foo[0]

. See Why is the address of an array equal to its value in C?

So when you wrote arr1 = arr2

, the compiler thinks that you are just referencing the address of the array, not the whole array. When you write the name of a structure, the compiler knows that you are referring to the structure as a whole, not just the first member.

0


source







All Articles