#Dynamic array length in structs
15 messages · Page 1 of 1 (latest)
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.
Arrays are by definition constant size
There is this thing called VLA, but you shouldn't use that anyways
!vla
A Variable Length Array (VLA) is an array where the size is not constant and depends on a variable.
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]
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.
: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
If you want to have a dynamically sized array then use pointers together with malloc or calloc
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);
}
btw, sizeof(char) is 1 by definition, so you can just omit it.
of course, just wasn’t sure what type they wanted for their array, so figured i’d give a general template
thanks
@proud oxide Has your question been resolved? If so, type !solved :)
!solved