3 ms·
"Dynamic array" refers to block of memory allocated via malloc() which you just happen to use as array. "Flexible array member" [0] is when you have a struct a
by Jorengarenar 4y ago
"Dynamic array" refers to block of memory allocated via malloc() which you just happen to use as array.
"Flexible array member" [0] is when you have a struct and its last member is an array with unspecified size.
An example:
#include <stdio.h>
#include <stdlib.h>
struct Foo {
int len;
int* arr; // dynamic "array"
};
struct Bar {
int len;
int arr[]; // FAM
};
int main()
{
const int n = 12;
// have to allocate myself; no guarante it will be nearby the rest of struct
struct Foo* a = malloc(sizeof a);
a->arr = malloc(n * sizeof *(a->arr));
// array is part of the memory allocated for struct
struct Bar* x = malloc((sizeof x) + n*(sizeof *(x->arr)));
return 0;
}
[0]: https://en.wikipedia.org/wiki/Flexible_array_member https://en.wikipedia.org/wiki/Flexible_array_member
- unnouinceput 4y ago>"Dynamic array" refers to block of memory allocated via malloc() which you just happen to use as array.< No. A dynamic array is an array which can be expanded or shrinked during its runtime life. The fact that C/C++ uses malloc for that (and btw, it's not the only way to do it) it's her problem. In other languages you have dynamic arrays that can be expanded/shrinked without using an extra line - main reason why nowadays Rust is a replacement for C/C++ >[0]< From you own wiki reference: "the flexible array member must be last" LMAO, really? Well, that indeed is a bigger C quirk. In Pascal, as an example, I can have it anywhere inside the record (struct equivalent of C), and it can be just as "flexible".
- blep_ 4y agoIt has to be last because it's not a pointer to the array, it is the array. The array elements are immediately after the struct in memory. You can't resize it without reallocating the whole struct.