![]() |
Pointer Program
I'm trying to understand a few things in this program I'm working with out of one of my books. Here is the code:
:
int *pn = new int [3];First it outputs the value at pn[1] which is 4. I'm okay with that. Then the pointer is incremented by 1. So at this point the pointer is now pointing to the second element, since when we started the pointer was pointing at the first element. So the output again is 4. What's a little confusing is when he says: :
cout << "pn[0] is: " << pn[0] << endl;He still is using the pn[0] subscript even though the pointer is really pointing to the second element in the array. He could have done this instead: :
cout << "pn[1] is: " << *pn << endl;To me that would have been clearer. But I guess the compiler knows that because you told the pointer to point now to the second element in the array, if you write pn[0], it will still output pn[1]. Correct? What I don't get also is this: :
cout << "pn[1] is: " << pn[1] << endl;Somehow this outputs the value of the last array element. But why? Nowhere in the code did the pointer get told to point to the last element. Why does pn[1] output the value of the last element? Just need a little help here. |
So like are the subscripts all being shifted over one place? Like sub[0] gets moved to sub[1] and sub[1] gets move to sub[2]?
|
Pointer arithmetic. pn[n] merely adds the value of n to the pointer (taking into account the size of the element). Once pn has been incremented, then pn [0] is the element the pointer is now pointing to and pn [1] is the next element.
Note that by incrementing pn, the coder has screwed up his reference to the dynamic memory. It can't be deleted unless the pointer is restored to its original value. Bad thing to do. Make a copy before manipulating. I recommend that the read the pointer material linked to in my signature. If you've read it, read it again. One of the headings is pointer arithmetic. |
:
int *pn = new int [3]; // creates an array of 3 integers in the free store |
pn[0] = pn (Always!)
pn[1] = pn+1 pn[2] = pn+2 This always holds. So if I do this: pn++; pn[0] = 4 pn[1] = 6 pn[2] = 8 then... pn[0] = 6 pn[1] = 8 pn[2] = ??? That's how you get those values. pn[2] would have some random number. |
You put your pn++ before the initialization; I think you meant after. Else, pn [0] still points to 4.
|
| All times are GMT -5. The time now is 2:45 AM. |
Powered by vBulletin® Version 3.7.0, Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Copyright ©2007 DaniWeb® LLC