I want to assign the struct a to the struct b. Printing the address and the values of the array before and after function call it shows that during the function call the assignment works and both pointers point to the same struct address. However, after returning from the function the changes are reversed. Why?
typedef struct arrayA {
int a[3];
}arrayA;
void f(arrayA *a, arrayA *b){
a = b;
printf("address of a: %p\n", a);
printf("address of b: %p\n", b);
}
int main(int argc, char *argv[]) {
printf("------------ Array assignment test -----------------\n");
arrayA a = { { 0, 0, 0} };
arrayA b = { { 1, 1, 1} };
printf("address of a: %p\n", &a);
printf("address of b: %p\n", &b);
printf("a[0] : %d a[1] : %d\n", a.a[0], a.a[1]);
f(&a, &b);
printf("a[0] : %d a[1] : %d\n", a.a[0], a.a[1]);
printf("address of a: %p\n", &a);
printf("address of b: %p\n", &b);
printf("----------------------------------------------------\n");
return 0;
}
Prints
------------ Array assignment test -----------------
address of a: 0x7ffd3fc17b80
address of b: 0x7ffd3fc17b90
a[0] : 0 a[1] : 0
address of a: 0x7ffd3fc17b90
address of b: 0x7ffd3fc17b90
a[0] : 0 a[1] : 0
address of a: 0x7ffd3fc17b80
address of b: 0x7ffd3fc17b90
----------------------------------------------------
a = b;. Standard beginner issue. Function parameters are passed by value in C. Modifications to parameters inside a function have no effect on the caller's variable.memcpy(a, b, sizeof(*b))or*a=*b.a=bin themainfunction works perfectly fine.a=binmainis equivalent to*a=*bin the function.