Docsity

Using pointers in c++ programming., Slides of C programming

Partial preview of the text

Download Using pointers in c++ programming. and more Slides C programming in PDF only on Docsity!

Pointers

and

dynamic objects

Topics

 Pointers

 Memory addresses

 Declaration

 Dereferencing a pointer

Pointers

 A pointer is a variable used to store the

address of a memory cell.

 We can use the pointer to reference this

memory cell

……^100100 ……^10241024 ……

Memory address: 1024 1032

integer (^) pointer

Pointer Types

 Pointer

 C++ has pointer types for each type of object

 (^) Pointers to int objects  (^) Pointers to char objects

 Even pointers to pointers

 (^) Pointers to pointers to int objects

Address Operator &

 The " address of " operator (&) gives the

memory address of the variable

 (^) Usage: &variable_name

……^100100 …… ……^ ……

Memory address: 1024

int a = 100; //get the value, cout << a; //prints 100 //get the memory address cout << &a; //prints 1024

a

Address Operator &

Memory address: 1024 1032

a

b #include

using namespace std; int main(){

int a, b; a = 88;

b = 100; cout << "The address of a is: " << &a << endl;

cout << "The address of b is: " << &b << endl; }

 (^) Result is: The address of a is: 1020 The address of b is: 1024

Dereferencing Operator *

 We can access to the value stored in the variable

pointed to by using the dereferencing operator (*),

Memory address: 1024 1032

int a = 100; int *p = &a; cout << a << endl; cout << &a << endl; cout << p << " " << *p << endl; cout << &p << endl;

 (^) Result is: 100 1024 1024 100 1032

a p

Don’t get confused

 (^) Declaring a pointer means only that it is a pointer: int

*p;

 (^) Don’t be confused with the dereferencing operator, which

is also written with an asterisk (*). They are simply two different tasks represented with the same sign int a = 100, b = 88, c = 8; int *p1 = &a, *p2, *p3 = &c; p2 = &b; // p2 points to b p2 = p1; // p2 points to a b = *p3; //assign c to b *p2 = *p3; //assign c to a cout << a << b << c;

Array Name is a pointer constant

#include using namespace std;

int main (){ int a[5]; cout << "Address of a[0]: " << &a[0] << endl << "Name as pointer: " << a << endl; }

Result : Address of a[0]: 0x0065FDE Name as pointer: 0x0065FDE

Dereferencing An Array Name

*#include using namespace std; void main(){ int a[5] = {2,4,6,8,22}; cout << a << " " << a[0]; } //main

a[4] 22

a[0]

a[2]

a[1]

a[3]

a

a

This element is called a[0] or *a