Reputation: 1
Q6: Dynamic Memory allocation: Consider the following declaration for the multi-level array, names:
char name_1[]= “John”;
char name_2[]= “Paul”;
char name_3[] = “Stephen”;
char *names[3]={name_1, name_2, name_3};
Create an equivalent multi-level array: dynamic_names that has all its elements and the data pointed to by its elements on the heap.
What exactly does this even mean? seems a little broad and with no direction to put me in... Would be very awesome to help!
Thanks!
Upvotes: 0
Views: 210
Reputation: 6116
Create an equivalent multi-level array: dynamic_names that has all its elements and the data pointed to by its elements on the heap.
The ...multi-level array with all its elements in heap... : char **dynamic_names;
(Only a pointer because the space will be allocated dynamically using malloc
).
Now the 3
elements in the array dynamic_names
i.e. ...the data pointed to by its elements... also need to be in heap, therefore, each of the char *name_1;
, char *name_2;
; char *name_3;
will also be allocated memory dynamically similarly using malloc
.
P.S. : I have explained the problem in words. Try to figure out how to write the code for it. :)
EDIT: (After OP's Comment)
More explanation:
The multi-level array dynamic_names
will point to 3
char*
pointers.
Each of the three pointers name_1
and similar will point to 1
char
array of different sizes.
To allocate a space of 5
chars
and assign it to a char *
pointer, you write:
char *ptr = malloc(5 * sizeof(char));
[Sincere Advice: Don't cast return value of malloc
]
EDIT 2:
char **dynamic_names = malloc(3*sizeof(char*));
This will allocate space for 3
char*
pointers, and assign the base address of the allocated space to dynamic_names
.
char *name_1 = malloc(10*sizeof(char));
This will allocate space for a string/array of size 10
(including '\0'
), and assign the base address of the space to name_1
.
strncpy(name_1, "John", 5);
This will initialize the space allocated for the first string (pointed to by name_1
) with "John"
.
dynamic_names[0] = name_1;
this will assign "the pointer to first string" as the first element of the dynamic_names
array.
Now you have to allocate space for other two strings and provide their base addresses to name_2
and name_3
and then assign these pointers as second and third elements resp. to dynamic_array
.
Upvotes: 1