Cisco Systems Interview Question
Got the code from some forum.
int main()
{
int i; /* general purpose variable used for loop index */
int j; /* general purpose variable used for loop index */
int **a; /* this is the array name */
int size_x; /* this variable will be used for the first dimension */
int size_y; /* this variable will be used for the second dimension */
/* suppose we want an array of int: a[5][3] */
size_x = 5;
size_y = 3;
/* allocate storage for an array of pointers */
a = malloc(size_x * sizeof(int *));
/* for each pointer, allocate storage for an array of ints */
for (i = 0; i < size_x; i++) {
a[i] = malloc(size_y * sizeof(int));
}
/* just for kicks, show the addresses (note: not all sequential) */
/* assign an arbitrary value to each element */
for (i = 0; i < size_x; i++) {
for (j = 0; j < size_y; j++) {
printf("&a[%d][%d] = %p\n", i, j, &a[i][j]); /* show the addresses */
a[i][j] = i * size_y + j; /* just some unique number for each element */
}
printf ("\n");
}
/* now show the contents that were assigned */
for (i = 0; i < size_x; i++) {
for (j = 0; j < size_y; j++) {
printf("a[%d][%d] = %2d\n", i, j, a[i][j]);
}
printf ("\n");
}
/* now for each pointer, free its array of ints */
for (i = 0; i < size_y; i++) {
free(a[i]);
}
/* now free the array of pointers */
free(a);
return 0;
}
int **a;
get row1 and col1
// allocate required space for given dimension
space1 = (int*) malloc(sizeof(int)*row1*col1);
// allocate row pointers
a = (int**) malloc(sizeof(int*)* row1);
// break regions and assign the row pointers
for(i=0; i<row1; i++)
a[i] = space1 +(i*col1);
//Advantage reduced number of mallocs
template<class T>
bool make2DArray(T**& x, int rows, int cols) {
try{
x = new T*[rows]; // S* x = new S[rows], with S = T*;
for (int i=0; i<rows; i++)
x[i] = new T[cols];
return true;}
catch (xallox) {return false;}
}
bool delete2DArray(T**& x, int rows) {
for (int i=0; i<rows; i++)
delete [] x[i];
delete [] x; // confirm this
x = 0; // x is just the null pointer
}
int * arr = (int * ) malloc(sizeof(int)*nrows*ncols);
- Anonymous November 22, 2009