cpp-pointers

14y, 199d ago [edited]

cpp Pointers

if p is a pointer

&p

the memory address of p

*p

the content that p points to

p

the content of p (or the address that p points to)

Dynamic memory allocation or alias

Useful but dangerous...

int *p, *q; // create two pointers, named p and q

p = new int; // 

*p = 100;

q = p;

*q = 200;

q = new int;

*q = *p;

delete p; // give memory that p occupied back to operating system

p = NULL; // set p to memory address 0  

delete q; // give memory that q occupied back to operating system

q = NULL; // set q to memory address 0

Dynamic Allocation for arrays

int size = 5;         // create an integer
int *A;               // create an array of pointers

A = new int[ size ];  // Ask for a certain size for your array

A[0] = 10;            // Give values to Array
A[1] = 20;
A[2] = 30;
A[3] = 40; 
A[4] = 50; 

//       8    32   32       36       40
cout << &A << A << A + 0 << A + 1 << A + 2

//       10      28      30
cout << A[0] << A[1] << A[2] 

//       10      10       28        30
cout << *A << *A + 0 << A + 1 << * A + 2

delete []A;
A = NULL;

Comments

hide preview ▲show preview ▼

What's next? verify your email address for reply notifications!

Leave first comment to start a conversation!