I am trying to create an array of strings in C using malloc
. The number of strings that the array will hold can change at run time, but the length of the strings will always be consistent.
I've attempted this (see below), but am having trouble, any tips in the right direction will be much appreciated!
#define ID_LEN 5 char *orderedIds; int i; int variableNumberOfElements = 5; /* Hard coded here */ orderedIds = malloc(variableNumberOfElements * (ID_LEN + 1));
Ultimately I want to be able to use the array to do this:
strcpy(orderedIds[0], string1); strcpy(orderedIds[1], string2); /* etc */
dynamically allocated arrays To dynamically allocate space, use calls to malloc passing in the total number of bytes to allocate (always use the sizeof to get the size of a specific type). A single call to malloc allocates a contiguous chunk of heap space of the passed size.
Space is allocated by calling malloc with the number of bytes needed (for strings this is always one more than the maximum length of the string to be stored): char *pc = malloc(MAXSTR + 1) ; // can hold a string of up to MAXSTR characters.
However, the malloc call (if it succeeds and returns a non- NULL result, and if n > 0 ) will create an anonymous array object at run time. But it does not "define an array a ". a is the name of a pointer object.
You should assign an array of char pointers, and then, for each pointer assign enough memory for the string:
char **orderedIds; orderedIds = malloc(variableNumberOfElements * sizeof(char*)); for (int i = 0; i < variableNumberOfElements; i++) orderedIds[i] = malloc((ID_LEN+1) * sizeof(char)); // yeah, I know sizeof(char) is 1, but to make it clear...
Seems like a good way to me. Although you perform many mallocs, you clearly assign memory for a specific string, and you can free one block of memory without freeing the whole "string array"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With