There is a difference with where the memory is allocated. Using array syntax, memory is allocated on the stack (assuming you are in a function), while malloc'ed arrays / bytes are allocated on the heap.
int a[1000]; int *b = malloc(1000 * sizeof(int))
Stack distribution is fast and often preferable if:
- Requires a "small" amount of memory.
- An array pointer should not be returned from a function
Heap allocation is slower, but has the following advantages:
- Available heap memory (usually) -> than available stack memory
- You can freely pass a pointer to allocated bytes, for example. returning it from a function - just remember to free it at some point.
The third option is to use statically initialized arrays if you have a common task that always requires a small array. Given that you can free the memory statically consumed by the array, you avoid heap memory, gain the flexibility to pass a pointer, and avoid tracking pointer ownership to free memory.
Edit: if you use C99 (by default with the gnu c compiler, I think?), You can make arrays of stacks of variable length, for example
int a = 4; int b[a*a];
toucan
source share