I am struggling to understand the code below, I understand that t is a multidimensional character variable ( 3 row and 3 columns), and p is a pointer or array of pointers, the array of pointers shouldn't be declared as:
int **p[3][3];
p= new int*[3]
instead of *p = (char *)t;
Can someone help me to understand the meaning of this declaration?.. thanks in advance
#include <iostream>
using namespace std;
int main() {
char t[3][3], *p = (char *)t;
for(int i = 0; i < 9; i++)
*p++ = 'a' + i;
cout << t[1][1];
return 0;
}
char t[3][3] allocates 9 chars in memory, something like:
1 2 3 4 5 6 7 8 9
[ ][ ][ ][ ][ ][ ][ ][ ][ ]
Next you let the pointer p point to the first allocated char ( *p = (char * )t
1 2 3 4 5 6 7 8 9
[ ][ ][ ][ ][ ][ ][ ][ ][ ]
*p
Knowing there are 9 allocated chars, you can now move the pointer forward with the statement *p++, so after first *p++
1 2 3 4 5 6 7 8 9
[ ][ ][ ][ ][ ][ ][ ][ ][ ]
*p
Then you insert the char 'a'+i into that memory location
1 2 3 4 5 6 7 8 9
[ ][a][ ][ ][ ][ ][ ][ ][ ]
*p
1 2 3 4 5 6 7 8 9
[ ][a][b][ ][ ][ ][ ][ ][ ]
*p
and so on...
Note operator precedence is important, ++ (postfix) has higher precedence than * (inderection), so first the pointer is incremented by one (++), and then the inderection gives 'access' to the allocated memory, if you prefer to be more explicit about it, you can use *(p++) instead.
whats happening is that it's declaring the variable p as having the same pointer as your 2D array t. That way it can access it without requiring nested forloops.
'graphically' the contents would be accessed something like this:
pointer in question.
T
->1 2 3
4 5 6
7 8 9
P
->1 2 3 4 5 6 7 8 9
If you have an array like this
char t[3][3];
then pointer to its first element can be declared like
char ( *p )[3] = t;
That is the pointer p
points to an object of type char[3]
. If to increase the pointer ++p
then the value in p
will be increased by the value equal to sizeof( char[3] )
that is p
will point to the second "row" of the array.
The value stored in p
after this declaration
char ( *p )[3] = t;
is equal to the value of the expression &t[0][0]
. The difference is the type of the objects pointed to by these pointers.
Thus you can write for example
char *p2 = reinterpret_cast<char *>( p );
So p2
and p
have the same value but increasing the pointer p2
moves it "right" to point to the second character of the array while increasing the pointer p
moves it "right" to point at once to the second "row" of the array.
So you can reinterpret the pointer p
as a pointer of type chsr *
to traverse the array character by character.
You can write either using C casting
char *p2 = (char *)t;
or using C++ casting
char *p2 = reinterpret_cast<char *>( t );
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.