#Dynamic array length in structs

15 messages · Page 1 of 1 (latest)

proud oxide
#

Hi is there away to declare dynamic array lenghts in structs?

struct ConfigParameters {
    char hostname[30];
    int portNumber;
    char gameKindName[30]
};

zealous jungleBOT
#

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.

weak sleet
#

There is this thing called VLA, but you shouldn't use that anyways

#

!vla

zealous jungleBOT
# weak sleet !vla
What Is a VLA, and Why Is It "Bad"?

A Variable Length Array (VLA) is an array where the size is not constant and depends on a variable.

Example
int size = rand();
int vla[size]; // VLA of type int[size]
int not_vla[10]; // regular array of type int[10]
constexpr int size = 10;
int arr[size]; // also not a VLA, of type int[10]
Why Are VLAs "Bad"?

VLAs have poor compiler support and can lead to unsafe code. The core issue with VLAs is that the compiler doesn't know the size of the stack frame. Without warning flags like -Wvla, it can be easy to create a VLA by accident, even in C++ with some compilers.

Compiler Support

:white_check_mark: available since C99
:no_entry: not available in C++ at all
:no_entry: was never supported by MSVC
:warning: optional feature since C11
:warning: supported as non-standard extension by GCC, clang

weak sleet
#

If you want to have a dynamically sized array then use pointers together with malloc or calloc

proud oxide
#

jep

#

but how can i use malloc in a struct

dawn hollow
#
struct s {
  size_t num_chars;
  char *buf;
};

int main() {
  struct s str;
  str.num_char = 50; // or whatever length
  str.buf = malloc(sizeof(char) * str.num_char);
}
weak sleet
dawn hollow
#

of course, just wasn’t sure what type they wanted for their array, so figured i’d give a general template

proud oxide
#

thanks

zealous jungleBOT
#

@proud oxide Has your question been resolved? If so, type !solved :)

proud oxide
#

!solved