Monday, August 21, 2006

2D array in function

char a[10];
char* p = a; // OK
Here 'p' is initialized to point to first element of 'a'.

Now consider
typedef char* CharPointer;
CharPointer ahum[10];
char** pp = ahum; // OK

This is also OK. 'ahum' is an array of 10 char* pointers, and 'pp' is a pointer to char*. 'pp' is initialized to point to the first element of 'ahum', which is a char* pointer just like all other elements of 'ahum'.

Finally consider

char argh[10][10];
char** pp = argh; // NOT OK.

'pp' is a pointer to char*, but is initialized to point to a char[10] array (the first element of 'argh' is a char[10] array).

if p is a two D array,
char p[2][123] = {"male", "female"}
Call in function with following ways:

void print(char p[][N], int len)
for(int i = 0 ; i < len ; ++i)
cout << p[i] << endl;

void print(const char p[][128], const int length)
for ( int i = 0; i < length; ++i )
std::cout << &p[i][0] << std::endl;

No comments:

Post a Comment