If you want to dynamically allocate arrays, you can use malloc
from stdlib.h
.
If you want to allocate an array of 100 elements using your words
struct, try the following:
words* array = (words*)malloc(sizeof(words) * 100);
The size of the memory that you want to allocate is passed into malloc
and then it will return a pointer of type void
(void*
). In most cases you'll probably want to cast it to the pointer type you desire, which in this case is words*
.
The sizeof
keyword is used here to find out the size of the words
struct, then that size is multiplied by the number of elements you want to allocate.
Once you are done, be sure to use free()
to free up the heap memory you used in order to prevent memory leaks:
free(array);
If you want to change the size of the allocated array, you can try to use realloc
as others have mentioned, but keep in mind that if you do many realloc
s you may end up fragmenting the memory. If you want to dynamically resize the array in order to keep a low memory footprint for your program, it may be better to not do too many realloc
s.