Dynamic memory allocation for pointer arrays Dynamic memory allocation for pointer arrays arrays arrays

Dynamic memory allocation for pointer arrays


In C a string is a char*. A dynamic array of type T is represented as a pointer to T, so for char* that would be char**, not simply a char* the way you declared it.

The compiler, no doubt, has issued some warnings about it. Pay attention to these warnings, very often they help you understand what to do.

Here is how you can start your testing:

char **aPtr;int len = 1; // Start with 1 stringaPtr = malloc(sizeof(char*) * len); // Do not cast malloc in CaPtr[0] = "This is a test";printf("%s",aPtr[0]); // This should work now.


char *str; //single pointer   

With this you can store one string.


To store array of strings you Need two dimensional character array

or else array of character pointers or else double pointer


char str[10][50]; //two dimensional character array

If you declare like this you need not allocate memory as this is static declaration


char *str[10];  //array of pointers 

Here you need to allocate memory for each pointer

loop through array to allocate memory for each pointer

for(i=0;i<10;i++) str[i]=malloc(SIZE);

char **str;    //double pointer

Here you need to allocate memory for Number of pointers and then allocate memory for each pointer .

str=malloc( sizeof(char *)*10);

And then loop through array allocate memory for each pointer

for(i=0;i<10;i++) str[i]=malloc(SIZE);


char * aPtr;

is as pointer to a character, to which you allocated memory to hold exactly 1 character.

Doing

aPrt[0] = "test";

you address the memory for this one characters and try to store the address of the literal "test" to it. This will fail as this address most likley is wider then a character.

A fix to your code would be to allocate memory for a pointer to a character.

char ** aPtr = malloc(sizeof(char *));aPtr[0] = "test";printf("%s", aPtr[0]);

Are more elegant and more over robust approach would be to allocate the same (as well as adding the mandatory error checking) by doing:

char ** aPtr = malloc(sizeof *aPtr);if (NULL == aPtr){  perror("malloc() failed");  exit(EXIT_FAILURE);}...