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?
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);
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".
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.
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.
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)), ...;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With