Change pointer to an array to get a specific array element
c++, pointers
Solution
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.
Problem
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; ```