0

In C, I am creating a datastructure that includes an array of pointers to another structure. The array is defined like this (the structure is called Bucket).

Bucket *b_array[];

This array is part of another structure, called Object for the sake of this question. The entire typedef then looks like this:

typedef struct Object {
    Bucket *b_array[];
} Object;

Now, a bit further in the program, I am using this array and I am trying to create a variable that holds a pointer to one of the buckets in the array. The function gets a pointer to an Object structure (obj_ptr)and the index (idx) of the bucket. The code looks as follows:

Bucket *at_idx = *(obj_ptr->b_array + idx);

Here is the problem: Upon executing this code, the at_idx variable becomes a null pointer. GDB can confirm this for me.

(gdb) p at_idx
$1 = (Bucket *) 0x0

However, the thing that I am trying to assign to at_idx is not null. This is also something that GDB can confirm. Even weirder, the exact same expression is used in an if-statement a couple lines earlier where I check *(obj_ptr->b_array + idx) == NULL and that returns false.

I am out of ideas of what is going on here, but it will probably be something simple that I'm missing.

Any help will be appreciated!

I am sorry for the possibly vague context of the code, but this issue is happening in a university assignment. Because of university policy I am not allowed to share my full code.

2
  • When did you allocate memory ? Commented Dec 3, 2020 at 20:01
  • @MaartenWeyns "Because of university policy I am not allowed to share my full code" - then provide a separate minimal reproducible example that demonstrates the same issue. Commented Dec 3, 2020 at 20:03

1 Answer 1

1
typedef struct Object {
    Bucket *b_array[];
} Object;

First of all C does allow variable size arrays in empty structures.

typedef struct Object {
    int a;
    Bucket *b_array[];
} Object;

You need to allocate memory for the variable size array (and the structure itself as well).

Object *obj = malloc(sizeof(*obj) + NELEMENTS * sizeof(obj -> b_array[0]));

Then you may start to assign the values to the array.

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

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.