So I’m transitioning from Java to C++ and am still having trouble trying to get my mind wrapped around how pointers work >.< Hope some of you seasoned C++ programmers can help me out!
In class we created both a stack and queue implementation using a dynamic array.
My teacher used pointers to create these arrays on the heap.
int* data = new int[25];
What I don’t understand is how can you insert values into the array with “data[top]”? I thought pointers just held the memory address? I would ask my teacher how this works but I’m on a time crunch and she won’t be able to get back to me till tomorrow afternoon >.<
Stack::push(int value) {
if(top==size) {
resize();
}
data[top] = value;
top++;
}
Yes, but you’re allowed to do things with that memory address. In particular C++ allows something called ‘pointer arithmetic’ which allows you to use a memory address to obtain the address of other memory located relative to the memory you already have the address for. E.g., if you have a memory address you can get the address of the memory located immediately after it.
(the squares are memory locations)
So an array is a series of memory locations. To access any element of the array you simply take the address you have, compute the address of the element you want to access, and then use that new address.
You don’t have to store the address you compute in a variable:
C++ provides a shorthand for the syntax
*(A+5), this is the array index operator:One thing that’s interesting is that the array index operator really is just shorthand for this
*(A+5)expression. Since you can flip around the operands and do*(5+A)you can do the same with the array index operator:You shouldn’t do that though, because it’s not very readable.
Another thing to know about pointers: Java has pointers. When you do
in Java
sis a pointer. Java just tries to hide this fact at the same time that it requires the use of pointers to a much greater extent than C++ does. Java doesn’t have pointer arithmetic, and you don’t have to manually dereference pointers in Java like you have to in C++. But consider:And remember those Null Pointer exceptions you get in Java.
If you’ve been using Java then you’ve already been using pointers. They’re not really all that different in C++, but they’re directly visible and explicit in C++ instead of being poorly hidden the way Java has them.