Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

arrays

c

malloc

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?

like image 438
user1779502 Avatar asked Mar 28 '13 16:03

user1779502


People also ask

How do you malloc an array of pointers?

Dynamically allocating an array of pointers follows the same rule as arrays of any type: type *p; p = malloc(m* sizeof *p); In this case type is float * so the code is: float **p; p = malloc(m * sizeof *p);

How do I use array of strings to pointers?

Arrays of pointers: (to strings)char *a[ ] = {"one", "two", "three"}; Here, a[0] is a pointer to the base add of string "one". a[1] is a pointer to the base add of string "two". a[2] is a pointer to the base add of string "three".

What is the output of C program with array of pointer to strings?

16) What is the output of C program with array of pointers to strings.? Explanation: It is an array of arrays. Using an array of pointers to strings, we can save memory.


2 Answers

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.

like image 186
Grijesh Chauhan Avatar answered Oct 03 '22 01:10

Grijesh Chauhan


This:

char** p = malloc(30 * sizeof(char*));

will allocate a buffer big enough to hold 30 pointers to char (or string pointers, if you will) and assign to p its address.

p[0] is pointer 0, p[1] is pointer 1, ..., p[29] is pointer 29.


Old answer...

If I understand the question correctly, you can either create a fixed number of them by simply declaring variables of the type message:

message msg1, msg2, ...;

or you can allocate them dynamically:

message *pmsg1 = malloc(sizeof(message)), *pmsg2 = malloc(sizeof(message)), ...;
like image 38
Alexey Frunze Avatar answered Oct 02 '22 23:10

Alexey Frunze