I was trying to get my old C-skills up to speed, but I have a small problem with pointers in arrays which are located in structs. Example:
#define ARRAYSIZE 3
struct B;
struct A {
int val;
};
struct B {
struct A *ptr;
int iter;
};
int main() {
struct A *a1;
struct A *a2;
struct A *a3;
struct A *a_array[3];
struct B *b_imp;
short i;
a1 = malloc(sizeof(struct A));
a2 = malloc(sizeof(struct A));
a3 = malloc(sizeof(struct A));
a1->val = 1;
a2->val = 2;
a3->val = 3;
a_array[0] = a1;
a_array[1] = a2;
a_array[2] = a3;
b_imp = malloc(sizeof(struct B));
b_imp->ptr = calloc(ARRAYSIZE, sizeof(struct A));
b_imp->iter = 0;
for (i = 0; i < ARRAYSIZE; i++) {
b_imp->ptr[b_imp->iter++] = *a_array[i];
}
a3->val = 5;
for (i = 0; i < b_imp->iter; i++) {
printf("Value: %d\n", b_imp->ptr[i].val);
}
return 0;
}
The problem is, that even though I change a3's value to 5, it still prints 3.
And this seems logical too; when I do b_imp->ptr[b_imp->iter++] = *a_array[i]; I think I'm copying the struct. But if try to *b_imp->ptr[b_imp->iter++] = a_array[i]; It just says pointer type required - of course.
What am I doing wrong? How can I just add a pointer to my structs, and not copy them?