In C:
When a struct is sent (via a parameter) by value in to a function, a new struct is created, so changing the structure inside the function won't change the original structure.
When an array is sent (via a parameter) by value in to a function, a new pointer is created, so changing the array inside the function won't change the original array, but changing array values inside the function (since we have the pointer to the original array) will change the values in the original array.
When a struct with an array field is sent (via a parameter) by value in to a function, ????? is created, so that changing the array (pointer) inside the function won't change the original array and changing array values won't change the values in the original array.
Does the third point mean that an array field of a struct, when sent in to a function will be entirely cloned? Why isn't just the pointer used instead? What does the specification say about it?
A piece of code that I've played with:
typedef struct {
int value;
int array[3]; /* initialized to 0 by default */
} Struct_t;
void foo(Struct_t structure)
{
printf("-- %p\n", structure.array); /* Pointer to local array */
structure.value = 1;
*structure.array = 1; /* Won't change the original array */
*(structure.array + 1) = 1; /* Won't change the original array */
structure.array[2] = 1; /* Won't change the original array */
}
int main()
{
Struct_t s = { .value = 0 };
foo(s);
printf("-- %p\n", s.array); /* Pointer to original array */
printf("%d\n", s.value);
printf("%d\n", s.array[0]);
printf("%d\n", s.array[1]);
printf("%d\n", s.array[2]);
}
Output:
-- 0x7ffe8f17d194
-- 0x7ffe8f17d1b4
0
0
0
0