1

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;
}
0

2 Answers 2

1

The problem is that A.b is not an array of structs, it is a pointer. You can make a pointer point to an array of structs, but it does not do so by default.

The simplest approach is to malloc the correct number of struct Bs into A.b at the beginning, and then put copies of the struct Bs 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 As into an array of their own would be a lot more complex.

Sign up to request clarification or add additional context in comments.

Comments

0
void insertArray(A *a, int element) {
        struct B b ;
        b.record1 = 100;
        b.record2 = 200;
        A->b[element] =  b;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.