How to dynamically allocate an array of strings in C?

If I have the number of elements in a var variable called totalstrings and var called a "row size" which is the row size for each element, how do I dynamically allocate an array called "array?"

This is an array of strings in C, not C ++.

Thanks!

+7
source share
4 answers

NOTE. My examples do not check for NULL returns from malloc () ... you really have to do this; You will encounter if you try to use the NULL pointer.

First you need to create an array of char pointers, one for each line (char *):

char **array = malloc(totalstrings * sizeof(char *));

Next, you need to allocate space for each row:

 int i; for (i = 0; i < totalstrings; ++i) { array[i] = (char *)malloc(stringsize+1); } 

When you finish using the array, you should remember free() about each of the pointers you allocated. That is, a loop through an array that calls free() for each of its elements, and finally free(array) .

+17
source

The general idiom for distributing an array N to M of any type T is

 T **a = malloc(N * sizeof *a); if (a) for (i = 0; i < N; i++) a[i] = malloc(M * sizeof *a[i]); 

According to the 1989 standard, you do not need to indicate the result of malloc , and in fact it is considered bad practice (it can suppress useful diagnostics if you forget to include stdlib.h or otherwise put on a prototype for malloc in the area). Early versions of C had a malloc return char * , so casting was necessary, but the likelihood that you would have to work with the compiler before 1989 was pretty far removed. C ++ requires execution, but if you write C ++, you must use the new operator.

Secondly, note that I am applying the sizeof operator to the selected object; the type of the expression *a is T * , and the type *a[i] is T (where in your case T == char ). This way you don't have to worry about keeping the sizeof expression in sync with the type of the selected object. IOW, if you decide to use wchar instead of char , you only need to make this change in one place.

+9
source
 char** stringList = (char**)malloc(totalStrings * sizeof(char*)); for( i=0; i<totalStrings; i++ ) { stringList[i] = (char*)malloc(stringSize[i]+1); } 
+3
source

Well, first you can allocate space for the "array", which will be the char * array, which is the "totalstrings" long.

What will be the starting and ending indices in the "array"? You know that the first one is 0; which last one?

Then, for each entry in the "array", you could (if you want) allocate one memory area that is "stringsize + 1" (why +1, pray, tell me?) For a long time by placing the starting address of this area - this line - in the correct member of the array.

That would be a good start, imo.

0
source

All Articles