An array struct is passed by value, not by reference

Using this guide I was told that arrays are passed by reference. This is done when the structure looks like this:

struct Person{
 char* name;
 int id;
}

      

But this is not the case when the structure looks like this:

struct Person{
 char name[20];
 int id;
}

      

When using the seconds structure, the array is name

copied by value:

struct Person p1 = {"John", 1234};
struct Person p2 = p1;
p2.name[0] = 'L';

// p1.name[0] is still 'K'

      

Why is this happening?

+3


source to share


3 answers


I was told that arrays are passed by reference.

This is not entirely true. Arrays are not passed at all, no function can take an array as an argument. When you declared the function

void foo(int bar[]);

      

the type of argument it takes foo

, in fact int *

, and when you call it



int arr[23];
/* fill arr with meaningful values */
foo(arr);

      

the pointer to the first element arr

is passed by value. All function arguments are passed by value in C without exception.

So when you pass to a struct Person

function that is passed by value, that's why the members are struct

copied. If one of the elements is an array which is also copied as it is part of struct

.

+2


source


This is true for both. The only difference is that for the first structure, you only store the pointer to the string and the id field. In the second structure, you store the entire string and id field in the structure. Therefore, the first structure is approx. 8 bytes in size (assuming a 32-bit pointer) and the second structure is approx. 24 bytes in size.

In both cases, the entire structure is copied if you call the function and pass it by value. You can check this by changing the id field instead of the name field.

The reason for passing structures and arrays to functions by reference (as a pointer) is to expel this copy onto the stack.



Edit: To clean up: by accessing p2.name [0] for the first structure, you are accessing a location outside of the (copied) structure somewhere else in memory (which is not copied). If you use p2.name [0] for the second structure, you access the location within the memory area allocated for the (copied) structure.

Looking through my code, I just found another important part here: Since you initialize the frist structure with string literals (hardcoded strings) by writing p2.name [0], you get undefined behavior (depending on the toolchain and operating system, from beyond which your program could even crash!)

+1


source


In the first case your structure contains a pointer to a character buffer, in the second it is actually a structure (read: holds space for storage) 20 characters.

So in the first case, when you are looping over a value, you are copying a pointer, not a value.

0


source







All Articles