54
POINTERS

Pointers It provides a way of accessing a variable without referring to its name. The mechanism used for this is the address of the variable

Embed Size (px)

Citation preview

Page 1: Pointers It provides a way of accessing a variable without referring to its name. The mechanism used for this is the address of the variable

POINTERS

Page 2: Pointers It provides a way of accessing a variable without referring to its name. The mechanism used for this is the address of the variable

PointersIt provides a way of accessing a variable

without referring to its name.

The mechanism used for this is the address of the variable.

Page 3: Pointers It provides a way of accessing a variable without referring to its name. The mechanism used for this is the address of the variable

Address of variableEach variable occupies some bytes in

memory (according to its size)Each byte of memory has a unique address so

that it can be accessed (just like the address of our homes)

Variable names are actually titles given to these addressesSuch as the ‘white house’

When we use a variable, the compiler fetches the value placed at its address or writes a new value to that address

Page 4: Pointers It provides a way of accessing a variable without referring to its name. The mechanism used for this is the address of the variable

Address of variableHow can we find the address of that variable?The “&” (Ampersand) operator returns the

address of a variable

cout << a << endl;cout << &a << endl;

Page 5: Pointers It provides a way of accessing a variable without referring to its name. The mechanism used for this is the address of the variable

PointersPointers are just variables storing numbers –

but those numbers are memory addressesA pointer that stores the address of some

variable x is said to point to x.A pointer is declared by putting a star (or '*')

before the variable name.To access the value of x, we’d need to

dereference the pointer.

Page 6: Pointers It provides a way of accessing a variable without referring to its name. The mechanism used for this is the address of the variable

Motivation for using PointersTo return more than one value from a function.To pass arrays and strings more conveniently

from one function to another.To manipulate arrays more easily by moving

pointers to them. Obtaining memory from the systemIn more advanced programming, such as

To create complex data structures, such as linked lists and binary trees

For dynamic memory allocation and de-allocation

Page 7: Pointers It provides a way of accessing a variable without referring to its name. The mechanism used for this is the address of the variable

PointersDeclaration of pointer to an int

int* intPtr;

Initializing a pointerint val = 42;int* intPtr = &val;

The ampersand (or '&') before val means "take the address of val".

The pointer intPtr is assigned the address of val, which is another way of saying that intPtr now points to val.

Page 8: Pointers It provides a way of accessing a variable without referring to its name. The mechanism used for this is the address of the variable

Pointers

0028F868

005465C7

Pointing to val

42

0028F868

val intPtr

Page 9: Pointers It provides a way of accessing a variable without referring to its name. The mechanism used for this is the address of the variable

PointersIf we print out the value of intPtr, we'll get the

address of val.

To get the data that intPtr actually points at, we have to dereference intPtr with the unary star

operator ‘*’ int val = 42;int *intPtr = &val;cout << "&val: " << &val << endl;//address of valcout << "intPtr: " << intPtr << endl; // ..again, addresscout << "*intPtr: " << *intPtr << endl; // displays 42

Note that the star (or '*') operator has many uses. When used in a binary context, it can mean multiplication. When used in a variable declaration, it means "this variable is a pointer". When used in an expression as a single-argument operator, it can mean "dereference". With so many uses, it's easy to get confused.

Page 10: Pointers It provides a way of accessing a variable without referring to its name. The mechanism used for this is the address of the variable

PointersSince intPtr points to val, any changes that we make

to val will also show up when we dereference intPtr:

int val = 42;int* intPtr = &val;cout << "val: " << val << endl; // displays 42cout<<"*intPtr: "<<*intPtr<<endl;//displays 42val = 999;cout << "val: " << val << endl;// displays 999cout << "*intPtr: " << *intPtr << endl; // displays 999

Page 11: Pointers It provides a way of accessing a variable without referring to its name. The mechanism used for this is the address of the variable

PointersYou can declare a pointer to any type, not just

int: char ch= ‘H’;char* chPtr = &ch;cout << “ch: " << ch<< endl;         cout << “chPtr: " << chPtr << endl;cout << "*chPtr: " << *chPtr << endl; *chPtr = "!";cout << "*chPtr: " << *chPtr << endl; cout << “ch: " <<ch<< endl;        

Page 12: Pointers It provides a way of accessing a variable without referring to its name. The mechanism used for this is the address of the variable

Pointersfloat val = 1.43;float* fltPtr = &val;cout << “val: " << val << endl;         // 1.43cout << “val: " << fltPtr<< endl; // addresscout << "*fltPtr: " << *fltPtr << endl; // 1.43*fltPtr = 3.1416;cout << "*fltPtr: " << *fltPtr << endl; //3.1416cout << “val: " << val << endl;         // 3.1416

Page 13: Pointers It provides a way of accessing a variable without referring to its name. The mechanism used for this is the address of the variable

Pointers and const Pointers can be declared const in three ways:

The pointer itself can be declared constThe data the pointer points (“the pointee”) can

be declared constBoth the pointer and the pointee can declared const

Page 14: Pointers It provides a way of accessing a variable without referring to its name. The mechanism used for this is the address of the variable

Pointers and const const pointer, which means that once initialized

it can't point at something else.

int val1 = 42;int * const intPtr = &val1;*intPtr = -1;        // okayint val2 = 999;intPtr = &val2;      // error!

Page 15: Pointers It provides a way of accessing a variable without referring to its name. The mechanism used for this is the address of the variable

Pointers and const const data, which means that the data that the

pointer points to can't be changed

int val1 = 42;const int * intPtr = &val1;*intPtr = -1;        // error!int val2 = 999;intPtr = &val2;      // okay

Page 16: Pointers It provides a way of accessing a variable without referring to its name. The mechanism used for this is the address of the variable

Pointers and const Both of the above -- you can change neither the

pointer nor the data it points to:

int val1 = 42;const int * const intPtr = &val1;*intPtr = -1;        // error!int val2 = 999;intPtr = &val2;      // error!

Page 17: Pointers It provides a way of accessing a variable without referring to its name. The mechanism used for this is the address of the variable

The variety of ways that you can use const can be confusing. One useful way to understand pointer declarations is to read them starting from the variable name reading from right to left . int * intPtr;  //the variable intPtr is a pointer to an int.

const int * intPtr; //the variable intPtr is a pointer to an int //that is constant. Since the int is constant, we can't change it. We //can change intPtr, however.

int * const intPtr; //the variable intPtr is a constant pointer //to an int. Since intPtr is constant, we can't change it. However, we //can change the int.

const int * const intPtr; //the variable intPtr is a constant pointer to // an int that is constant. Everything is constant.

Pointers and const

Page 18: Pointers It provides a way of accessing a variable without referring to its name. The mechanism used for this is the address of the variable

Exampleint main ( ){ int x=4, y=7; int *px, *py; px = &x; //int *px=&x; py = &y; //int *py=&y; cout << “x = ” << x<<“y =”<<y; *px = *px + 10; *py = *py + 10; cout << “x = ” << x<<“y =”<<y; return 0;}

Page 19: Pointers It provides a way of accessing a variable without referring to its name. The mechanism used for this is the address of the variable
Page 20: Pointers It provides a way of accessing a variable without referring to its name. The mechanism used for this is the address of the variable

Discussionint main (void)

{ int a; int *ptr1; char c; char *ptr2; int fred; ptr2=&c; ptr1=&fred; ptr1=&a ;

//ok. Char pointer init with add of a char//ok. int pointer init with the address of

an int

//ok. int pointer init with the address of an int

Page 21: Pointers It provides a way of accessing a variable without referring to its name. The mechanism used for this is the address of the variable

Discussionptr2=&fred; ptr2=&'#'; ptr2=&25; ptr2=&(a +3);}

// NO. cannot assign the address of an int to a char

// NO. cannot take the address of an implicit constant// NO. cannot take the address of an implicit constant

// NO. cannot take the address of an expression

Page 22: Pointers It provides a way of accessing a variable without referring to its name. The mechanism used for this is the address of the variable

Discussionint main()

{ int c,a=10;int *p1=&a;c=*p1; *p1=*p1**p1; (*p1)++; c=*&a;}

//equivalent expression "c=a"

//equivalent expression "a=a*a"//equivalent expression "a++"

//equivalent expression "c=a"

Page 23: Pointers It provides a way of accessing a variable without referring to its name. The mechanism used for this is the address of the variable

Discussionint a = 3;int b = 4;int *pointerToA = &a;int *pointerToB = &b;int *p = pointerToA;p = pointerToB;cout<< a << b << *p; // Prints 344

Page 24: Pointers It provides a way of accessing a variable without referring to its name. The mechanism used for this is the address of the variable

Pointer to Pointerint k=4,*ptr, **ptoptr;

ptr=&kptoptr=&ptr;

USECreation of dynamically sizeable arraysUse of new and delete

Page 25: Pointers It provides a way of accessing a variable without referring to its name. The mechanism used for this is the address of the variable
Page 26: Pointers It provides a way of accessing a variable without referring to its name. The mechanism used for this is the address of the variable

int main (){

int x = 1;int *px = &x;int **ppx = &px;

cout << "x = " << x << endl;

*px = x+10;cout << "x = " << x << endl;

**ppx = *px + x;cout << "x = " << x << endl;

return 0;}

Page 27: Pointers It provides a way of accessing a variable without referring to its name. The mechanism used for this is the address of the variable

int main (){

int x = 1;int *px = &x;int **ppx = &px;

cout << "x = " << x << endl;

*px = x+10;cout << "x = " << x << endl;

**ppx = *px + x;cout << "x = " << x << endl;

return 0;}

Page 28: Pointers It provides a way of accessing a variable without referring to its name. The mechanism used for this is the address of the variable

Pointers and Arrays In c++, you can treat pointers and arrays very

similarily:

int array[ ] = {3,1,4,1,5,9};int* arrayPtr = array;cout<<"array[0]: ” <<array[0] << endl;//displays 3cout<<"arrayPtr[0]: "<<arrayPtr[0]<<endl;//displays 3arrayPtr++;cout<<"arrayPtr[0]: "<<arrayPtr[0]<<endl; // displays 1array++; // error: arrays are const

Page 29: Pointers It provides a way of accessing a variable without referring to its name. The mechanism used for this is the address of the variable

Pointers and Arrays

Arrays and pointers may be used interchangeably, but you can change what pointers point at, whereas arrays will always "point" to the same thing.

Page 30: Pointers It provides a way of accessing a variable without referring to its name. The mechanism used for this is the address of the variable

Pointers and Arrays// Using pointers to print out values from array

int main ( ){int nums [5] = {92,81,70,69,58}; int dex ; for ( dex = 0; dex <5; dex++ )

cout << *(nums + dex)<<“ ”;}

* ( nums + dex ) is same as nums [ dex ].

Page 31: Pointers It provides a way of accessing a variable without referring to its name. The mechanism used for this is the address of the variable
Page 32: Pointers It provides a way of accessing a variable without referring to its name. The mechanism used for this is the address of the variable

Pointers and Arraysint * ptr; /* pointer to int (or int array) */

char *chptr; /*pointer to char(or char array)*/

int table[3]= {5, 6, 7}; /* array */

ptr = table; //&table[0]//*assign array address to pointer*/

cout << *ptr; /*prints 5*/cout << *(ptr+1); /* prints 6 */

Page 33: Pointers It provides a way of accessing a variable without referring to its name. The mechanism used for this is the address of the variable

Multi Dimensional Arrays (Matrices)An array can have two or more

dimensions. This permits them to model multidimensional objects, such as graph paper or the computer display screen.

They are often used to represent tables of values consisting of information arranged in rows and columns.

Page 34: Pointers It provides a way of accessing a variable without referring to its name. The mechanism used for this is the address of the variable

Multi Dimensional Arrays (Matrices)To identify a particular element, we must

specify two subscripts. By convention, array_name[row_number][col_number]

For example, arr[i][j]

Page 35: Pointers It provides a way of accessing a variable without referring to its name. The mechanism used for this is the address of the variable

2-D Array (Matrix)

Page 36: Pointers It provides a way of accessing a variable without referring to its name. The mechanism used for this is the address of the variable

Initializing a 2D Arrayint matrix [10] [2] = { {59 , 78},

{14 , 17}, {68 , 28}, {32 , 45}, { 5 , 14}, {12 , 15}, { 6, 2},

{ 22, 1}, {14 , 16}, { 2, 58} };

The values used to initialize an array are separated by commas and surrounded by braces.

Page 37: Pointers It provides a way of accessing a variable without referring to its name. The mechanism used for this is the address of the variable

2-D Array (Matrix)

59(0,0

)

78(0,1

)

14(0,2

)

17(0,3

)

68(1,0

)

28(1,1

)

32(1,2

)

45(1,3

)

5(2,0

)

14(2,1

)

12(2,2

)

15(2,3

)

6(3,0

)

2(3,1

)

22(3,2

)

1(3,3

)4 x 4 Matrix

int matrix [4] [4] = { {59, 78,14, 17},{68, 28,32, 45}, {5, 14,12, 15} ,{6, 2, 22, 1} };

(row = 2, col = 0)

Page 38: Pointers It provides a way of accessing a variable without referring to its name. The mechanism used for this is the address of the variable

Reading a 2D Arrayint matrix [4][4]={{59,78,14,17},{68,28,32,45}, {5, 14,12,15},{6,2, 22, 1}}; for(int i=0;i<4;i++){

for(int j=0;j<4;j++){

cout<<matrix[i][j]<<"\t"; } cout<<endl;

}

Page 39: Pointers It provides a way of accessing a variable without referring to its name. The mechanism used for this is the address of the variable

ExampleWrite a matrix with following entries

12 12

54 34

16 3

12 6

43 23

1 2

Page 40: Pointers It provides a way of accessing a variable without referring to its name. The mechanism used for this is the address of the variable

Task!!Device a code for filling a 2-D matrix

Page 41: Pointers It provides a way of accessing a variable without referring to its name. The mechanism used for this is the address of the variable

int main(void){ int matrix[5][2];

for(int i=0;i<5;i++) for(int j=0;j<2;j++) { cout<<"enter value for row "<<i<<" and

col“<<j<<": "; cin>>matrix[i][j];}

cout<<"the input matrix is \n";

for(int i=0;i<5;i++){

for(int j=0;j<2;j++)cout<<matrix[i][j]<<"\t";

cout<<endl;}

}

Page 42: Pointers It provides a way of accessing a variable without referring to its name. The mechanism used for this is the address of the variable

Pointers to 2D Arraysb[5] => *(b+5)int a[5][5];a[2][2] => *(*(a+2)+2)

Page 43: Pointers It provides a way of accessing a variable without referring to its name. The mechanism used for this is the address of the variable

const int ROWS = 3;const int COLS = 3;int main (){

int arr[ROWS][COLS] = {1,2,3} , {2,4,6} , {3,6,9}};

for (int i = 0; i <ROWS; i++){

for(int j = 0; j < COLS; j++)cout << *(*(arr+i)+j) << " ";

cout << endl;}return 0;

}

Page 44: Pointers It provides a way of accessing a variable without referring to its name. The mechanism used for this is the address of the variable

Equivalent Expressionsint a[n][m];

a[n][m]*(*(a+n)+m)*(a[n]+m)(*(a+n))[m]

Page 45: Pointers It provides a way of accessing a variable without referring to its name. The mechanism used for this is the address of the variable

Pointers and Functions/* test function that returns two values */void rets2 (int* , int* ); /*prototype*/int main ( )

{int x, y; /* variables*/ rets2 ( &x, &y ); /*get values from function*/ cout <<“First is = ”<< x<<“Second is = ”<<y;}

/* returns two numbers */void rets2 ( int* px, int* py )

{ *px= 3; /* set contents of px to 3 */ *py = 5; /* set contents of px to 5 */}

Page 46: Pointers It provides a way of accessing a variable without referring to its name. The mechanism used for this is the address of the variable

Reference ArgumentsReference is an alias to a variable.Reference arguments are indicated by ‘&’ after the data

type, e.g. float& xThe ‘&’ indicates that ‘x’ is an alias to whatever variable is

being passed as an argument. So,

power(base, exp); //function call void power(float& x, float& y) // function header

‘x’ is a reference to the float type variable ‘base’ being passed to the function.

Page 47: Pointers It provides a way of accessing a variable without referring to its name. The mechanism used for this is the address of the variable

Reference ArgumentsUsage:

Passing arguments (both scalar and array) to functions.

Advantages: The actual variable can be accessed instead of its

copy. Provides a mechanism for returning more than one

value from the function back to the calling program.Disadvantages:

It allows the function to make changes in the original variable so caution must be taken while passing by reference.

Page 48: Pointers It provides a way of accessing a variable without referring to its name. The mechanism used for this is the address of the variable

Passing a Variable By Referencevoid power(float&, int); // prototypevoid main(void) {float base,

int exp =3; cout<< "enter the number whose power you want to find";

cin >> base;

power(base, exp);cout <<"result = " <<base ;}

void power(float& x, int y){int product=1;for(int j=1; j<=y; j++)

product=product*x;X=product;}

Prototype includes &

function call is the same

header includes &

Page 49: Pointers It provides a way of accessing a variable without referring to its name. The mechanism used for this is the address of the variable

Pointers and ReferencingReference and pointers have a more or less

similar function. However, there are some fundamental differences in how they work.

Reference is an alias to the variable, while pointer gives the address of the variable.

References basically function like pointers that are dereferenced every time they are used.

Page 50: Pointers It provides a way of accessing a variable without referring to its name. The mechanism used for this is the address of the variable

Pointers and ReferencingHowever, because you cannot directly access

the memory location stored in a reference (as it is dereferenced every time you use the reference), you cannot change the location to which a reference points, whereas you can change the location to which a pointer points.

Page 51: Pointers It provides a way of accessing a variable without referring to its name. The mechanism used for this is the address of the variable

Passing Arrays by ReferenceThere are 3 ways of passing an array to a

functionBy value – element by elementBy referenceBy pointers

Page 52: Pointers It provides a way of accessing a variable without referring to its name. The mechanism used for this is the address of the variable

Passing Arrays by ReferenceIn passing by value a copy of each of the

element of the array being passed is made. This copy is then used by the function.The elements of the original array can’t be

modifiedIn case of very large arrays this method is

inefficient as it would require a lot of processing and would take up a considerable amount of space.

Page 53: Pointers It provides a way of accessing a variable without referring to its name. The mechanism used for this is the address of the variable

Passing Arrays by ReferenceFunction prototype or declaration

void somefunct( int [], int);

Function call void somefunct(elem, size)

Function Headervoid somefunct( int array[], int

size_of_elem)

Page 54: Pointers It provides a way of accessing a variable without referring to its name. The mechanism used for this is the address of the variable

Passing an Array By Referencevoid display(int [],int);

int main ( ){

int num [5] = {23,43,56,34,32};display ( num, 5 );

}

void display ( int j[], int n ){

int i;for (i=0; i<n; i++)

cout <<"\n element "<<i <<" = "<< j[i];}