Using this guide I was told that arrays are passed by reference. This holds when a struct looks like this:
struct Person{
char* name;
int id;
}
But is doesn’t when the struct looks like:
struct Person{
char name[20];
int id;
}
When using the seconds struct, The name array is 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?
That’s not quite true. Arrays aren’t passed at all, no function can take an array as an argument. When you have a function declared
the type of argument that
footakes is actuallyint *, and when you call ita pointer to the first element of
arris passed by value. All function arguments are passed by value in C, without exception.Thus when you pass a
struct Personto a function, that is passed by value, hence the members of thestructare copied. If one of the members is an array, that is copied too, since it is a part of thestruct.