C++/Pointers, Pointer to Pointers, and New[]
Expert: Zlatko - 2/8/2010
QuestionHey Zlatko,
I ran into a runtime error where I was (apparently) writing out of bounds for my array on the heap. Now I'm not great at pointers so I traced the derefrencing a million times and I can't figure out why I'm out of bounds. Here's a sample code that reenacts the problem:
1 int main()
2 {
3 int five = 5;
4 int* pt = new int[five];
5 int** pntr = &pt;
6 pt[3] = 2;
7 *pntr[3] = 3;
8 return 0;
9 }
The error occurs on line 7. "Access violation writing location ..."
However, pt[0] = 2; *pntr[0] = 3; works fine. (Stops working at [1], well within my array size.)
If it makes any difference I am using Visual C++ 2008 Express.
Thank you for your time,
Jordan
AnswerHello Jordan.
Here's a handy reference
http://www.difranco.net/cop2220/op-prec.htm
The problem is that the square brackets are evaluated first, then the de-referencing * operator.
When you say *pntr[3], its saying *(pntr +3), but you want (*pntr)[3], so you need to put in the brackets.
Notice that pntr is not an array, so (pntr+3) is not memory you want to reference.
With the brackets, first pntr is de-referenced to give you the pt, then the third element pointed at by pt is assigned.
Is that clear to you?
Best regards
Zlatko