Location in Memory

I have this code

1
2
3
4
5
6
7
8
9
10
11
12
13
int main()
{ 
   int a[] = { 22, 33, 44, 55, 66, 77, 88, 99 };
   int* p = &a[3];                              
   cout << "p = " << p << ", *p = " << *p;
   cout << "\n&a = " << &a;                     
   cout << "\n&p = " << &p;                     
   cout << "\n&(a[5]) = " << &(a[5]);           
   cout << "\n&(*(a+5)) = " << &(*(a+5));
   cout << "\n&(*(p+2)) = " << &(*(p+2));
   cout << "\n&(p+2) = " << p+2; //&(p+2);
   cout << endl;
}


How would I point p to a different location in memory?
simply assign it a new address:

1
2
3
4
5
6
int main () 
{
    int a[] = {22 , 33 , 44 , 55 , 66 , 77 , 88 ,99 };
    int* p = &a[3];
    int* p = &a[6];
}
Even if I want to change it to this 0x0012FF50?
Check out this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include<iostream>
using namespace std;

int main (){
int T[5] = {7, 3, 11, 7, 3};
cout << &T << "   "<<int(&T) << endl;       // show me the adress of T[0], both hex and decimal
int *p = T;                                 // you don´t need & cause an array´s name is essentially an adress to its first cell
cout << p << "   "<<int(p) << endl;         // show me where p points to, both hex and decimal
cout << *(p + 1) << endl;                  // show me what´s on the second cell
cout << p[1] << endl;                       // show me what´s on the second cell
cout << * (T + 1) << endl;                   // see how T and *p are interchangeable??
cout << T[1] << endl;

p++;                                       // move pointer p to next position in memory (actually, second cell of int array)
cout << p << "   "<<int(p) << endl;           // show me where p new adress, it´s moved four Bytes!!!
cout << *p << endl;                          // second cell of the array
}


The central ideas are:
1) you can see an adress as a decimal base number (more familiar)
2) when you add one to a pointer, it moves a number of Bytes that is proportional to the variable type (int -> 4, double, -> 8, bool -> 1, etc.)
3) The name of an array is a pointer to its first cell.
4) *p and T are interchangeable.
5) you don´t need to tell the pointer the exact adress, in fact, a variable location may change from execution to execution of your program. You tell the pointer to "follow" a variable, or move one cell forwards/backwards.

Good luck!!!
Topic archived. No new replies allowed.