Basic and Advance C Question:
How can I dynamically allocate arrays?
Answer:
The equivalence between arrays and pointers allows a pointer to malloc'ed memory to simulate an array quite effectively. After executing
#include <stdlib.h>
int *dynarray;
dynarray = malloc(10 * sizeof(int));
(and if the call to malloc succeeds), you can reference dynarray[i] (for i from 0 to 9) almost as if dynarray were a conventional, statically-allocated array (int a[10]). The only difference is that sizeof will not give the size of the ``array''
#include <stdlib.h>
int *dynarray;
dynarray = malloc(10 * sizeof(int));
(and if the call to malloc succeeds), you can reference dynarray[i] (for i from 0 to 9) almost as if dynarray were a conventional, statically-allocated array (int a[10]). The only difference is that sizeof will not give the size of the ``array''
Previous Question | Next Question |
What should malloc(0) do? Return a null pointer or a pointer to 0 bytes? | What is wrong with this initialization? |