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;
}
The problem is that Ab
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 Ab
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.
void insertArray(A *a, int element) {
struct B b ;
b.record1 = 100;
b.record2 = 200;
A->b[element] = b;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.