J K
J K

Reputation: 1

Dynamic Memory Allocation and multi-level arrays in C

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

Answers (1)

0xF1
0xF1

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:

  1. The multi-level array dynamic_names will point to 3 char* pointers.

  2. Each of the three pointers name_1 and similar will point to 1 char array of different sizes.

  3. 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:

  1. 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.

  2. 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.

  3. strncpy(name_1, "John", 5); This will initialize the space allocated for the first string (pointed to by name_1) with "John".

  4. dynamic_names[0] = name_1; this will assign "the pointer to first string" as the first element of the dynamic_names array.

  5. 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

Related Questions