Get a pointer to built-in 3D char array?!

In some cases like when some application needs to describe arguments and options it supports, there is a further need to pass a pointer to that description, but my experience show, it can result in a segfault.
I tried to describe like this:
char i[4][2][100] = { {"AA","aa"}, {"BB","bb"}, {"CC","cc"}, {"\0","\0"} };

Direct access to i is successful:
1
2
for ( int j=0;i[j][0][0];j++ )
cout << i[j][0] << endl;


But, if pointer is used, it segfaults:
1
2
3
char*** T = (char***) i;
for ( int j=0;T[j][0][0];j++ )
cout << T[j][0] << endl;


Please, this an ugly obstacle in the way. When finished, I could send a code in a single header file to manage program options and arguments effectively, maybe it is worth looking at now?
Yup, char[][][] is not the same as char***.

The compiler knows this, but obeys your explicit typecast on line 1 because explicit typecasts overrides the compiler's type checking mechanism.

So there is NO way to enter my char[][][] in source file and then use it as char*** and dynamic memory allocation is therefore compulsive?
No. Dynamic memory allocation is required.

The declaration char i[4][2][100] allocates exactly 4 * 2 * 100 = 800 bytes of memory beginning at address A and ending at address A + 799. The expression "i" results in the value A. Notice that the only values the compiler thinks are in memory are the 800 characters... no pointers.

The declaration char*** i allocates exactly 4 bytes of memory (assuming 32-bit pointers) beginning at address A and ending at address A + 3. The declaration says that the value stored at A through A+3 is in fact another pointer value (it is a pointer to a "pointer-to-pointer-to-char". So notice that the compiler thinks that there are three pointers values in memory.

So no pointers in the first case, three in the second. This is why it won't work, and this is why pointers aren't exactly the same thing as arrays.
It's possible to use a different accessing method, though:
1
2
3
4
5
char * T=(char *)i;
int width=100,
	height=width*2;
for ( int j=0;T[height*j];j++ )
	std::cout <<T+height*j<<std::endl;
Last edited on
Thank you for participating ...
Topic archived. No new replies allowed.