user3810155
user3810155

Reputation:

Deep Copy of Struct Member Arrays

I have found this behaviour just right now, in the recent gcc.

Is such deep copying guaranteed behaviour by the C/C++ standard so okay to rely upon?

[edit] And what is the logic behind such behaviour? C array objects when copied with the = operator or as a function argument will always be regarded as a plain pointer. What is different about struct members?

#include <stdio.h>
#include <stdlib.h>

typedef struct
{
    int arr[5];
}
array;

int main(void)
{
    array a = {{ 1, 2, 3, 4, 5}};
    array b;
    int i;

    b = a;
    b.arr[0] = 0;
    b.arr[1] = 0;
    for (i = 0; i < 5; i++)
    {
        printf("%d %d\n", a.arr[i], b.arr[i]);
    }
    return EXIT_SUCCESS;
}

will output,

1 0
2 0
3 3
4 4
5 5

Upvotes: 0

Views: 2128

Answers (1)

Yes, this is indeed guaranteed behaviour. An array is not a pointer. An array is a contiguous sequence of elements, and its value is the value of all of its elements. So copying the array must mean copying all of its elements.

You're saying C objects copied with = or as function arguments are always treated as a pointer. That's not quite correct - C (and C++) arrays cannot be copied by =. And functions cannot have parameters (or return types) of array type - these are always adjusted to pointer type. And function arguments of array type undergo array-to-pointer conversion to match.

So the basic rule is: arrays are copied by value. The exception part is that functions cannot have parameters (and return values) of array type, pointers are silently used instead.

Upvotes: 1

Related Questions