Reputation:
I am trying to build dynamic array with nested structs. When insert an item I am getting the following. error: incompatible types when assigning to type ‘struct B’ from type ‘struct B *’
What is the issue and where i am doing the mistake. Please help.
typedef struct {
size_t used;
size_t size;
struct B {
int *record1;
int *record2;
} *b;
} A;
void insertArray(A *a, int element) {
struct B* b = (struct B*)malloc(sizeof(struct B));
A->b[element] = b;
}
Upvotes: 1
Views: 247
Reputation: 2631
void insertArray(A *a, int element) {
struct B b ;
b.record1 = 100;
b.record2 = 200;
A->b[element] = b;
}
Upvotes: 0
Reputation: 726489
The problem is that A.b
is not an array of struct
s, it is a pointer. You can make a pointer point to an array of struct
s, but it does not do so by default.
The simplest approach is to malloc
the correct number of struct B
s into A.b
at the beginning, and then put copies of the struct B
s right into that array.
void initWithSize(struct A *a, size_t size) {
a->size = size;
a->b = malloc(sizeof(struct B) * size);
}
void insertArray(A *a, int index, struct B element) {
assert(index < a->size); // Otherwise it's an error
// There's no need to malloc b, because the required memory
// has already been put in place by the malloc of initWithSize
a->b[index] = element;
}
A slightly more complex approach would be using flexible array members of C99, but then the task of organizing struct A
s into an array of their own would be a lot more complex.
Upvotes: 1