Answers/Solutions to Exercises in Chapter 7, Exercise 4
E4: Implement a dynamic array of strings in the form of a dynamic array of pointers to strings. Implement it similarly to two-dimensional character array, where each string is stored in a row of different size.
S4: A sample program is below.
#include <stdlib.h>
#include <string.h>
// function main ------------------------------------------
int main()
{
int i;
char **array;
array = (char **) malloc(sizeof(int*)*4); // 4 strings
array[0]=(char*) malloc(strlen("string1")+1);
strcpy(array[0],"string1");
array[1]=(char*) malloc(strlen("this string2")+1);
strcpy(array[1],"this string2");
array[2]=(char*) malloc(strlen("this is string3")+1);
strcpy(array[2],"this is string3");
array[3]=(char*) malloc(strlen("this is string4 - the last one")+1);
strcpy(array[3],"this is string4 - the last one");
for(i=0; i<4; i++)
printf("array[%d]=%s\n",i,array[i]);
return 0;
}// end main
The run of the sample solution program:
array[0]=string1 array[1]=this string2 array[2]=this is string3 array[3]=this is string4 - the last one
Back to Answers/Solutions Index Back to Answers/Solutions for Chapter 7 Index