#Undefined array size in struct C

1 messages · Page 1 of 1 (latest)

plucky briar
#

I created the following 2 structs:

typedef struct my_struct_element{
  int key;
  int value;
  struct my_struct_element *next;
} my_struct_element;

typedef struct my_struct{
  int size;
  my_struct_element arr[];
} my_struct;

It's a part of a simple hashtable implementation that I am trying to accomplish. Now the problem that I have is that the size of my hashtable isn't fixed, and therefore when I call sizeof(my_struct), I don't get actually the size of my struct. Am I going down on the wrong path here, and should I use a pointer instead of my array? Like

my_struct_element* arr = malloc(sizeof(my_struct_element)*arr_size);
my_struct ms = {arr_size, arr}; 

But this way the my_struct instance is on the stack, not the heap, and only my array is on the heap.
Any good advice would be appreciated

latent warrenBOT
#

When your question is answered use !solved to mark the question as resolved.

Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For tips on how to ask a good question use !howto ask.

umbral canyon
#

Literally the same

#

If you want a dynamically sized array you always need to heap allocate it (slight simplification but good enough for now)

#

Also it really doesn't matter that your struct instance is on the stack and your arr is on the heap

plucky briar
#
my_struct* ms = malloc(sizeof(my_struct));
ms->size = 10;
ms->arr = malloc(sizeof(my_struct_element)*ms->size);
#

would work just fine?

umbral canyon
#

I mean this way both ms and the underlying arr are heap allocated and you will need to free both individually, but yeah, this works.

plucky briar
#

Oh, right, that was the original plan, so this is okay. I was just confused then of the size of arr. It won't be included the size of ms because arr is just a pointer, which is 8 bytes on my architecture

#

Thank you for the clarification! 😄

umbral canyon
#

👍