Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically create an array of strings with malloc

Tags:

arrays

c

malloc

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 */ 
like image 814
Chris Avatar asked May 09 '11 11:05

Chris


People also ask

Can you dynamically allocate an array?

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.

Can we use malloc for string?

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.

Can malloc be used for arrays?

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.


1 Answers

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"

like image 117
MByD Avatar answered Sep 18 '22 14:09

MByD