Answers/Solutions to Exercises in Chapter 7, Exercise 2
E2: Write a simple C program in which a two-dimensional dynamic arrays is used. Now add a function that adds a new row to the array. How complicated was it?
S2: A sample such program is below.
// function main ------------------------------------------
int main()
{
int i, j, **array;
array = (int**) malloc(sizeof(int*)*4); // 4 rows
for(i=0; i<4; i++) {
array[i]=(int*) malloc(sizeof(int)*3); // 3 columns
for(j=0; j<3; j++)
array[i][j]=10*i+j;
}
for(i=0; i<4; i++)
for(j=0; j<3; j++)
printf("array[%d][%d]=%d\n",i,j,array[i][j]);
return 0;
}// end main
Now add a function to add an extra row:
#include <stdlib.h>
// function add_row -----------------------------------------
void add_row(int** array,int rows)
{
int j;
// and a new row
array = (int**) realloc(array,sizeof(int*)*(rows+1));
array[rows]=(int*) malloc(sizeof(int)*3);
for(j=0; j<3; j++)
array[rows][j]=10*rows+j;
}// end add_row
// function main ------------------------------------------
int main()
{
int i, j, **array;
array = (int**) malloc(sizeof(int*)*4); // 4 rows
for(i=0; i<4; i++) {
array[i]=(int*) malloc(sizeof(int)*3); // 3 columns
for(j=0; j<3; j++)
array[i][j]=10*i+j;
}
for(i=0; i<4; i++)
for(j=0; j<3; j++)
printf("array[%d][%d]=%d\n",i,j,array[i][j]);
// and a new row
add_row(array,4);
// now display it again
for(i=0; i<5; i++)
for(j=0; j<3; j++)
printf("array[%d][%d]=%d\n",i,j,array[i][j]);
return 0;
}// end main
It is simple, as long as add_row() "knows" the index of the last row. Because a dynamic two-dimensional array is in fact a linked data structure, it is simple to attach one more row to it, nothing else must be changed --- with the exception of the actual one-dimensional array of pointers to individual rows. That's why we need to you realloc() there.
Back to Answers/Solutions Index Back to Answers/Solutions for Chapter 7 Index