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"
Answer from MByD on Stack OverflowYou 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"
char **orderIds;
orderIds = malloc(variableNumberOfElements * sizeof(char*));
for(int i = 0; i < variableNumberOfElements; i++) {
orderIds[i] = malloc((ID_LEN + 1) * sizeof(char));
strcpy(orderIds[i], your_string[i]);
}
Okay so basically I have a function that takes in a string and counts the lowercase tokens in it. I need to make a function that then returns an array of the lowercase tokens. I would need to use malloc to allocate enough memory for such array but I don’t know how to go about doing so.
Once the array is allocated how would I put the token strings into the array?
Any help is appreciated thank you
C programming 2d dynamic string array
Without malloc, how is the array of strings making use of dynamic memory allocation?
dynamic array of strings - C++ Forum
Dynamic String in array - C++ Forum
Videos
While I can understand the below is an example of static memory allocation while working on string arrays (2-dimensional character arrays): https://preview.redd.it/rndsb5zpgj7b1.png?width=1600&format=png&auto=webp&v=enabled&s=84cfe98ba875fee94947163de2b05ffb8c94650c
In order to optimize, dynamic memory allocation is the way in which for each string literal once \0 encountered, that marks the end of that string. Malloc should find a way into the code of such programs. However, I could not see the usage of Malloc or stdlib.h library in the below example: https://preview.redd.it/g44301m9hj7b1.png?width=1600&format=png&auto=webp&v=enabled&s=a29543a7a335f71c77d9014195661e7e9ef9ac30
Source: https://www.geeksforgeeks.org/array-of-strings-in-c/