Presentation is loading. Please wait.

Presentation is loading. Please wait.

POINTERS.

Similar presentations


Presentation on theme: "POINTERS."— Presentation transcript:

1 POINTERS

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.

3 Address of variable Each 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 addresses Such 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

4 Address of variable cout << &a << endl;
How can we find the address of that variable? The “&” (Ampersand) operator returns the address of a variable cout << a << endl; cout << &a << endl;

5 Pointers Pointers are just variables storing numbers –but those numbers are memory addresses A 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.

6 Motivation for using Pointers
To 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 system In more advanced programming, such as To create complex data structures, such as linked lists and binary trees For dynamic memory allocation and de-allocation

7 Pointers Declaration of pointer to an int int* intPtr;
Initializing a pointer int 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.

8 Pointers Pointing to val 42 0028F868 val 0028F868 005465C7 intPtr

9 Pointers If 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 val cout << "intPtr: " << intPtr << endl;   // ..again, address cout << "*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.

10 Pointers Since 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 42 cout<<"*intPtr: "<<*intPtr<<endl;//displays 42 val = 999; cout << "val: " << val << endl;// displays 999 cout << "*intPtr: " << *intPtr << endl; // displays 999

11 Pointers You 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 << “ch: " <<ch<< endl;        

12 Pointers float val = 1.43; float* fltPtr = &val; cout << “val: " << val << endl; // 1.43 cout << “val: " << fltPtr<< endl; // address cout << "*fltPtr: " << *fltPtr << endl; // 1.43 *fltPtr = ; cout << "*fltPtr: " << *fltPtr << endl; // cout << “val: " << val << endl; //

13 Pointers and const Pointers can be declared const in three ways:
The pointer itself can be declared const The data the pointer points (“the pointee”) can be declared const Both the pointer and the pointee can declared const

14 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;        // okay int val2 = 999; intPtr = &val2;      // error!

15 Pointers and const int val1 = 42; const int * intPtr = &val1;
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

16 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!

17 Pointers and const 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.

18 Example int 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; return 0; }

19

20 Discussion int 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

21 Discussion ptr2=&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

22 Discussion int 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"

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

24 Pointer to Pointer int k=4,*ptr, **ptoptr; ptr=&k ptoptr=&ptr; USE
Creation of dynamically sizeable arrays Use of new and delete

25

26 int main () { int x = 1; int. px = &x; int
int main () { int x = 1; int *px = &x; int **ppx = &px; cout << "x = " << x << endl; *px = x+10; **ppx = *px + x; return 0; }

27 int main () { int x = 1; int. px = &x; int
int main () { int x = 1; int *px = &x; int **ppx = &px; cout << "x = " << x << endl; *px = x+10; **ppx = *px + x; return 0; }

28 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 3 cout<<"arrayPtr[0]: "<<arrayPtr[0]<<endl;//displays 3 arrayPtr++; cout<<"arrayPtr[0]: "<<arrayPtr[0]<<endl; // displays 1 array++; // error: arrays are const

29 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.

30 Pointers and Arrays int main ( )
// 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 ].

31

32 Pointers and Arrays int * 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 */

33 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.

34 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]

35 2-D Array (Matrix)

36 Initializing a 2D Array int 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.

37 2-D Array (Matrix) int matrix [4] [4] = { {59, 78,14, 17},{68, 28,32, 45}, {5, 14,12, 15} ,{6, 2, 22, 1} }; 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) (2,1) 12 (2,2) 15 (2,3) 6 (3,0) 2 (3,1) 22 (3,2) 1 (3,3) (row = 2, col = 0) 4 x 4 Matrix

38 Reading a 2D Array int 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;

39 Example Write a matrix with following entries 12 54 34 16 3 6 43 23 1

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

41 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"; cout<<matrix[i][j]<<"\t"; cout<<endl;

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

43 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;

44 Equivalent Expressions
int a[n][m]; a[n][m] *(*(a+n)+m) *(a[n]+m) (*(a+n))[m]

45 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 */

46 Reference Arguments Reference is an alias to a variable.
Reference arguments are indicated by ‘&’ after the data type, e.g. float& x The ‘&’ 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.

47 Reference Arguments Usage: Advantages: Disadvantages:
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.

48 Passing a Variable By Reference
Prototype includes & void power(float&, int); // prototype void 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; function call is the same header includes &

49 Pointers and Referencing
Reference 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.

50 Pointers and Referencing
However, 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.

51 Passing Arrays by Reference
There are 3 ways of passing an array to a function By value – element by element By reference By pointers

52 Passing Arrays by Reference
In 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 modified In 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.

53 Passing Arrays by Reference
Function prototype or declaration void somefunct( int [], int); Function call void somefunct(elem, size) Function Header void somefunct( int array[], int size_of_elem)

54 Passing an Array By Reference
void 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];


Download ppt "POINTERS."

Similar presentations


Ads by Google