C++/Pointers, Pointer to Pointers, and New
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()
3 int five = 5;
4 int* pt = new int[five];
5 int** pntr = &pt;
6 pt = 2;
7 *pntr = 3;
8 return 0;
The error occurs on line 7. "Access violation writing location ..."
However, pt = 2; *pntr = 3; works fine. (Stops working at , well within my array size.)
If it makes any difference I am using Visual C++ 2008 Express.
Thank you for your time,
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, its saying *(pntr +3), but you want (*pntr), 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?