Originally Posted by
tw0nk
Hi I am getting this error with my code as I try to pass a 2d array into a function :
If anyone could be of any help i woule be extremely gratefull as I have been stuck on it for quite a while now. thanks in advance.
Program calculations that determine the address of an element of a two-dimensional array are different from those of an element an array of arrays.
Suppose you have the following:
Code:
int ary2d[numrows][numcols];
Then for ints i and j, the the program calculates the address of ary2d[i][j] like this (using pointer arithmetic for ints):
address of ary2d[i][j] = (address of ary2d[0][0]) + i * numcols + j
on the other hand, if you have this:
Code:
int **ppint;
ppint = new int * [pnumrows];
for (i = 0; i < pnumrows; i++) {
ppint[i] = new int[pnumcols];
}
Then for ints i and j, the program calculates the address of ppint[i][j] like this (using pointer arithmetic for ints):
address of ppint[i][j] = *(address of ppint[i]) + j
Bottom line:
For both cases the programmer can refer to elements by array terminology.
Code:
ppint[i][j] = xxx;
ary2d[i][j] = xxx;
Within the scope of the definitions of ppint and ary2d, there is no difference in how they are used (the compiler keeps track of how the addresses are calculated for the elements).
But you can't make a single function that will handle both.
Consider the following:
One function is defined like this:
Code:
void func1 (int **abc, int row, int col)
{
int xxx = abc[row][col]
// do something with it
}
Another function is defined like this
Code:
void func2(int xyz[][numcols], int row, int col)
{
int xxx = xyz[row][col];
// do something with it
}
1. You cannot invoke func1 with an argument that is a 2d array
2. You can invoke func1 with an argument that is an array of pointers to int, since that's semantically the same as a pointer to a pointer to an int.
3. You cannot invoke func2 with an argument that is a pointer to a pointer to int.
4. You can invoke func2 that is a pointer to an array[numcols] of int. (Note: this is (*p)[ncols], not *p[ncols])
5. Definition and prototype of func2 must explicitly have numcols, where numcols is a const integral type. That is to say that, for function definitions with 2D array arguments, the first dimension of a 2D array is free, the second must be specified.
Regards,
Dave