开发者

pointer array question in C++

I realize theres a lot of array and pointer questions, but I had one thats extremely specific... Its actually from a test I took in class awhile ago and I'm still having trouble with it.

The question is - Write out a complete declaration for

A variable name开发者_Go百科d pmatrix that is a pointer to an array of 8 arrays of 10 pointers to integers

so far I'm thinking something like

int*pmatrix[8][10] ,

more concerned with a good explanation than just an answer.

thanks!


A variable named pmatrix that is a pointer:

*pmatrix

to an array of 8

(*pmatrix)[8]

arrays of 10

(*pmatrix)[8][10]

pointers to integers:

int *(*pmatrix)[8][10]

Substituting into cdecl, we are told the following:

declare pmatrix as pointer to array 8 of array 10 of pointer to int

which is where we started!


int*pmatrix[8][10]

There's an issue of precedence: [] has a higher precedence than '*', so that is an array[8] of array[10] of pointer to int. You need to add parentheses to override the precedence:

int (*pmatrix)[8][10]

(More parentheses are possible. I'm not sure that

int (((*pmatrix)[8])[10]);

would be an improvement, however:-).)


The answer to your question would be

int* (*pmatrix)[8][10];

Remember though, arrays are just pointers to the first element of the array, so an array is a pointer and a pointer is an array (sometimes of just one element).

Note though, that beneath this array is really just a single-dimensional array of 80 elements. If you do an index like this:

int pmatrix[8][10];
pmatrix[3][5];

The compiler treats that as if you did:

*(pmatrix + (3 * 10) + 5);

because the index [3][5] accesses the 5th element (+ 5) of the 3rd subarray (3 * 10 (10 being the size of each sub array)).


int** pmatrix = new int*[8]; // Array of 8 pointers to arrays
for(int i = 0; i < 8; ++i) pmatrix[i] = new int[10]; // Create each array
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜