2d Array Checking / Error Handling?

Dear All,

I've just started learning C++ and am wondering if there is a way of checking whether a passed array is 2d? (The reason I've mentioned Error Checking in the title is because I'm wondering if this can be done by trying to reference, say, array[0][0] and seeing if an error arises, but then I don't know how error-trapping works in C++)
(T is a common placeholder meaning "any type".)

There's only one way, and it may not necessarily work:
T f(T array[width][height]);

In order to do array[0][0], one of these two conditions have to be met:
* 'array' is of type T[][]. That is, it was declared as T array[][]={/*...*/};, or T array[width][height];
* 'array' is of type T**.
Dereferencing is done at run time, but these conditions will be checked by the compiler at compile time, so there's really no point in doing it.
Even if that wasn't the case, if you were to dereference something you shouldn't dereference, the OS is likely to crash your program.

Bottom line, there is no sure-fire way to know that the pointer that was passed points to something that makes sense. The function should just assume that it does and give the responsibility of passing valid data to the caller.
Last edited on
The only way you would know is if you had function overloading, whereby one function would accept only one array as an argument and another function that accepted two, and recognised the activity within that function.
Thanks Helios.

McLeano: Could this be done so one function only accepts a 1d-array and the other a 2d-array?
Last edited on
one function would accept only one array as an argument and another function that accepted two, and recognised the activity within that function.
What? That doesn't make any sense.
What? That doesn't make any sense.


Sorry I misread the OP problem. I thought he said two different arrays.
You can

1
2
3
4
5
6
7
8
9
10
11
template< typename T, size_t N >
void foo( T (&array)[ N ] )
{
     // This function accepts 1D arrays
}

template< typename T, size_t N1, size_t N2 >
void foo( T (&array)[ N1 ][ N2 ] )
{
     // This function accepts 2D arrays
}


HOWEVER, this works only for fixed-length arrays. Neither of the above functions would suffice
for:

1
2
3
int** p2Darray;
// .... make a 2d array ....
foo( p2Darray );   // Will not compile; foo( int** ) does not exist 

I think this will do the job jsmith. Thanks. Could you explain to be what a template is though please, or perhaps provide a link to what you think is a decent explanation of it?
Topic archived. No new replies allowed.