Answers/Solutions to Exercises in Chapter 7, Exercise 3
E3: Take the program from exercise 2 and add a function that adds a new column to the array. How complicated was it in comparison to exercise 2?
S3: A sample program is below.
#include <stdlib.h> // function add_column ----------------------------------------- void add_column(int** array,int rows,int columns) { int i; for(i=0; i<rows; i++) { array[i]=(int*) realloc(array[i],sizeof(int)*(columns+1)); array[i][columns]=10*i+columns; } }// end add_column // 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 column add_column(array,4,3); // now display it again for(i=0; i<4; i++) for(j=0; j<4; j++) printf("array[%d][%d]=%d\n",i,j,array[i][j]); return 0; }// end main
Note, that this is more complex, in comparison to Exercise 2. Why? We have to extend or reallocate every row in the array, so a lot of memory handling is involved.
Back to Answers/Solutions Index Back to Answers/Solutions for Chapter 7 Index