How to allocate array of pointers for strings by malloc in C?

arrays, c, malloc

Solution

As I can understand from your assignment statement in while loop I think you need array of strings instead:

char** new_array;
new_array = malloc(30 * sizeof(char*)); // ignore casting malloc

Note: By doing `=` in while loop as below:

new_array [i] = new_message->array_pointers_of_strings [i];

you are just assigning address of string (its not deep copy), but because you are also writing "only address of strings" so I think this is what you wants.

Edit: waring "assignment discards qualifiers from pointer target type"

you are getting this warning because you are assigning a `const char*` to `char*` that would violate the rules of const-correctness.

You should declare your new_array like:

const  char** new_array;      

or remove `const` in declaration of 'array_pointers_of_strings' from message stricture.

Problem

I have this struct in C Example: ``` typedef struct { const char * array_pointers_of_strings [ 30 ]; // etc. } message; ``` I need copy this array_pointers_of_strings to new array for sort strings. I need only copy adress. ``` while ( i < 30 ) { new_array [i] = new_message->array_pointers_of_strings [i]; // I need only copy adress of strings } ``` My question is: How to allocate new_array [i] by malloc() for only adress of strings?

Original source