Answers/Solutions to Exercises in Chapter 7, Exercise 5

E5: In C, implement an integer dynamic two-dimensional pseudo-array that is always stored in a contiguous segment of memory and using the row-major approach. For access you have to use two functions, Get(i,j) to fetch a value and Set(i,j,value)to set a value. Because you need these two access functions, we call it a pseudo-array. In C++, implement it as a class that allows the proper indexing x[i][j].

S5:  A sample C program for the first part is below.

#include <stdlib.h>

int* array=NULL;
int row_size;

// function Get -------------------------------------------
int Get(int i,int j)
{
	if (array==NULL) {
		printf("array empty\n");
		exit(1);
	}
	return *(array+i*row_size+j);
}// end Get


// function Set -------------------------------------------
void Set(int i,int j,int value)
{
	if (array==NULL) {
		printf("array empty\n");
		exit(1);
	}
	*(array+i*row_size+j)=value;
}//end Set


// function main ------------------------------------------
int main()
{
	int i, j;

	row_size=2;
	array = (int*) malloc(sizeof(int)*3*row_size);  // 3 rows, 2 columns 
	for(i=0; i<3; i++)
	 for(j=0; j<row_size; j++)
	  Set(i,j,10*i+j);

	for(i=0; i<3; i++)
	 for(j=0; j<row_size; j++)
	  printf("array[%d][%d]=%d\n",i,j,Get(i,j));
    return 0;
}// end main

The output of the sample C program:

array[0][0]=0
array[0][1]=1
array[1][0]=10
array[1][1]=11
array[2][0]=20
array[2][1]=21

A sample C++ program:

#include <iostream.h>


// we need this class just to facilitate double indexing
class Row
{
protected:
	static int *fake_row; // we implement it as static to save space
public:
	Row() { fake_row=0; }
	Row& Convert(int* p) { fake_row=p; return *this; }
	int& operator[] (int j) { return fake_row[j]; }
};
int *Row::fake_row; // implementation of fake_row

class Array
{
protected:
	int *array;
	int col;
	Row fake; // just to facilitate the row indexing
public:
	Array(int rows,int columns) { array=new int[rows*columns]; col=columns; }
	~Array() { if (array!=0) delete[] array; }
	Row& operator[] (int i) { return fake.Convert((int*) &array[i*col]); }
};


// function main ------------------------------------------
int main()
{
	Array array(3,2);
	int i, j;

	for(i=0; i<3; i++)
	 for(j=0; j<2; j++)
	  array[i][j]=10*i+j;
	
	for(i=0; i<3; i++)
	 for(j=0; j<2; j++)
	  cout << "array[" << i<< "][" << j << "]=" << array[i][j] << '\n';
	
	
    return 0;
}// end main

The output the sample C++ program:

array[0][0]=0
array[0][1]=1
array[1][0]=10
array[1][1]=11
array[2][0]=20
array[2][1]=21

Back to Answers/Solutions Index                          Back to Answers/Solutions for Chapter 7 Index