Because of an assignment at Uni, I face the weird problem of having to initialize a struct to a pointer provided as a function parameter. Everything appears fine inside of that init function, but once I try to access the objects's values inside a different function, they just appear to be empty.
As I'm horrible at explaining things, I got a small example with actual and expected output:
#include <stdlib.h>
#include <stdio.h>
struct foo {
int bar;
};
void init_foo(struct foo* f) {
f = malloc(sizeof(struct foo));
f->bar = 5;
printf("bar0: %d\n", f->bar);
}
void print_foo(struct foo* f) {
printf("bar1: %d\n", f->bar);
}
int main() {
struct foo f;
init_foo(&f);
print_foo(&f);
}
Acutal output:
bar0: 5
bar1: 0
Expected output:
bar0: 5
bar1: 5
I haven't dealt with C all that much before, so if someone could provide an explanation and/or a solution to this, I'd be very thankful.