0

I got an assignment where I need to send an array of size N randomly generated numbers to a msg queue, msg queues need to be used with structs but how can I define the size of array in said struct from user input?

struct my_msg {
  long int msg_type;
  char some_text[];

so to be more specific lets say user enters 7 as the size of the array how do I make it into some_text[7] but after already defining the struct?

chqrlie
  • 131,814
  • 10
  • 121
  • 189
  • Why must the struct already be defined? … or is this an assumption? – S3DEV May 29 '22 at 18:31
  • @S3DEV arent we supposed to always define structs that we will be using in code at the beginning before main func? and I'm scanf-ing the user input in main so I cant pass it to an already defined object – Hashem Touqan May 29 '22 at 18:36
  • You could either use a pointer or [flexible array memeber](https://stackoverflow.com/questions/20310207/what-are-the-real-benefits-of-flexible-array-member) and then allocate the wanted memory – Bob__ May 29 '22 at 18:39
  • @Bob__ would it be somethhing like this?```struct my_msg* Message = malloc(sizeof(struct Message) + size * sizeof(int));``` – Hashem Touqan May 29 '22 at 18:47
  • Yeah, pretty much, if you want to use a FAM. Have your teachers already taught you that, though? – Bob__ May 29 '22 at 18:55
  • @HashemTouqan That might waste memory because `sizeof(struct Message)` includes padding. The `some_text` is also `char`, not `int`. Your size will also not be suitable to allocate an array, if that is desired. The size is `size_t size = offsetof(struct Message, some_text) + text_size;` for a single message and `size = (size + _Alignof(struct Message) - 1) & ~(_Alignof(struct Message) - 1);` to correct for arrays. – Goswin von Brederlow May 29 '22 at 21:09

0 Answers0