I am curious to why one cannot modify the variables of a struct when passed as a parameter into a function. I understand that the parameter is pass by value but when passing a struct variable you are passing its reference as the value.
Surely C doesn't create a copy of the struct on the stack, because the value of the struct reference being passed in is the same as the value of passing a pointer of the struct into a function.
#include <stdio.h>
#include <stdlib.h>
typedef struct String {
char* name;
int x;
} String;
/* Func Protos */
void foo(String str);
void bar(String * str);
void banjo(String str);
int main() {
String str = *(String *)malloc(sizeof(String));
str.x = 5; /* x == 5 */
foo(str); /* x == 5 still */
printf("%d\n", str.x);
banjo(str); /* x == 5 still */
printf("%d\n", str.x);
bar(&str); /* and of course, x = 0 now */
printf("%d\n", str.x);
}
void foo(String str) {
printf("%d\n", str); /* Same value as if we passed String * str */
str.x = 0;
}
void bar(String * str) {
printf("%d\n", *str);
str->x = 0;
}
void banjo(String str) {
printf("%d\n", str);
String * strptr = &str; /* This should be identical to passing String * str */
strptr->x = 0;
}
Produces this output:
3415000
5
3415000
5
3415000
0
Any help would be much appreciated!