I understand the overall meaning of pointers and references(or at least I think i do), I also understand that when I use new I am dynamically allocating memory.
My question is the following:
If i were to use cout << &p
, it would display the "virtual memory location" of p
.
Is there a way in which I could manipulate this "virtual memory location?"
For example, the following code shows an array of int
s.
If I wanted to show the value of p[1]
and I knew the "virtual memory location" of p
, could I somehow do "&p + 1
" and obtain the value of p[1]
with cout << *p
, which will now point to the second element in the array?
int *p;
p = new int[3];
p[0] = 13;
p[1] = 54;
p[2] = 42;
Sure, you can manipulate the pointer to access the different elements in the array, but you will need to manipulate the content of the pointer (i.e. the address of what p is pointing to), rather than the address of the pointer itself.
int *p = new int[3];
p[0] = 13;
p[1] = 54;
p[2] = 42;
cout << *p << ' ' << *(p+1) << ' ' << *(p+2);
Each addition (or subtraction) mean the subsequent (prior) element in the array. If p points to a 4 byte variable (e.g. int on typical 32-bits PCs) at address say 12345, p+1 will point to 12349, and not 12346. Note you want to change the value of what p contains before dereferencing it to access what it points to.
Not quite. &p
is the address of the pointer p
. &p+1
will refer to an address which is one int*
further along. What you want to do is
p=p+1; /* or ++p or p++ */
Now when you do
cout << *p;
You will get 54. The difference is, p
contains the address of the start of the array of ints, while &p
is the address of p. To move one item along, you need to point further into the int array, not further along your stack, which is where p
lives.
If you only had &p
then you would need to do the following:
int **q = &p; /* q now points to p */
*q = *q+1;
cout << *p;
That will also output 54 if I am not mistaken.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With