Pointers in C++. Topics Covered Introduction to Pointers Pointers and arrays Character Pointers,...

32
Pointers in C++

Transcript of Pointers in C++. Topics Covered Introduction to Pointers Pointers and arrays Character Pointers,...

Page 1: Pointers in C++. Topics Covered  Introduction to Pointers  Pointers and arrays  Character Pointers, Arrays and Strings  Examples.

Pointers in C++

Page 2: Pointers in C++. Topics Covered  Introduction to Pointers  Pointers and arrays  Character Pointers, Arrays and Strings  Examples.

Topics Covered

Introduction to Pointers Pointers and arrays Character Pointers, Arrays and Strings Examples

Page 3: Pointers in C++. Topics Covered  Introduction to Pointers  Pointers and arrays  Character Pointers, Arrays and Strings  Examples.

Introduction to Pointers When we declare a variable some memory is allocated for it.

The memory location can be referenced through the identifier “i”. Thus, we have two properties for any variable : its address and its data value. The address of the variable can be accessed through the referencing operator “&”. “&i” gives the memory location where the data value for “i” is stored.

A pointer variable is one that stores an address. We can declare pointers as follows int* p; .This means that p stores the address of a variable of type int.

Page 4: Pointers in C++. Topics Covered  Introduction to Pointers  Pointers and arrays  Character Pointers, Arrays and Strings  Examples.

Introduction to Pointers Q: Why is it important to declare the type of the variable that a

pointer points to? Aren’t all addresses of the same length? A: It’s true that all addresses are of the same length, however

when we perform an operation of the type “p++” where “p” is a pointer variable, for this operation to make sense the compiler needs to know the data type of the variable “p” points to. If “p” is a character pointer then “p++” will increment “p” by one byte (typically), if “p” were an integer pointer its value on “p++” would be incremented by 2 bytes (typically).

Page 5: Pointers in C++. Topics Covered  Introduction to Pointers  Pointers and arrays  Character Pointers, Arrays and Strings  Examples.

Introduction to Pointers Summary of what was learnt so far:

Pointer is a data type that stores addresses, it is declared as follows: int* a; char* p; etc.

The value stored in a pointer p can be accessed through the dereferencing operator “*”.

The address of a memory location of a variable can be accessed through the reference operator “&”.

Pointer arithmetic: only addition and subtraction are allowed. Type *ptr=&var int x=5; int *ptr=&x;

Page 6: Pointers in C++. Topics Covered  Introduction to Pointers  Pointers and arrays  Character Pointers, Arrays and Strings  Examples.

Pointers and Arrays The concept of array is very similar to the concept of pointer.

The identifier of an array actually a pointer that holds the address of the first element of the array.

Therefore if you have two declarations as follows: “int a[10];” “int* p;” then the assignment “p = a;” is perfectly valid Also “*(a+4)” and “a[4]” are equivalent as are “*(p+4)” and “p[4]”

. The only difference between the two is that we can change the

value of “p” to any integer variable address whereas “a” will always point to the integer array of length 10 defined.

Page 7: Pointers in C++. Topics Covered  Introduction to Pointers  Pointers and arrays  Character Pointers, Arrays and Strings  Examples.

Character Pointers, Arrays and Strings What is a String?

A string is a character array that is ‘\0’ terminated. E.g. “Hello”

What is a Character array? It is an array of characters, not necessarily ‘\0’ terminated E.g. char test[4] = {‘a’, ‘b’, ‘c’, ‘d’}; <this char array is not zero

terminated> What is a character pointer?

It is a pointer to the address of a character variable. E.g. char* a; <this pointer is not initialized>

Page 8: Pointers in C++. Topics Covered  Introduction to Pointers  Pointers and arrays  Character Pointers, Arrays and Strings  Examples.

Print location of pointer

#include<iostream.h> main() {int x=5; int *ptr=&x; cout<<"location Ptr="<<ptr; cout<<"\nlocation var="<<&x; cout<<"\nvalue Ptr="<<*ptr; cout<<"\n value var="<<x; system("pause"); }

Page 9: Pointers in C++. Topics Covered  Introduction to Pointers  Pointers and arrays  Character Pointers, Arrays and Strings  Examples.

Change value of pointer

#include<iostream.h>main(){int g=5;int *ptr=&g; *ptr=32;cout<<"\nx="<<g;system("pause");}

Page 10: Pointers in C++. Topics Covered  Introduction to Pointers  Pointers and arrays  Character Pointers, Arrays and Strings  Examples.

#include<iostream.h> main() {int g=15,item; int *ptr=new int [1]; *ptr=32; item=*ptr; *ptr=g; g=item; cout<<"\ng="<<g<<"\n*ptr="<<*ptr; system("pause");

}

Page 11: Pointers in C++. Topics Covered  Introduction to Pointers  Pointers and arrays  Character Pointers, Arrays and Strings  Examples.

Array in pointer #include<iostream.h> main() { int i, first_array[5]={34,26,43,23,54}; int *ptr=& first_array[0]; for(i=0;i<5;i++){ *(ptr+i)=*(ptr+i)+14; cout<<"\n first_array["<<i<<"]="<<*(ptr+i);} system("pause"); }

Page 12: Pointers in C++. Topics Covered  Introduction to Pointers  Pointers and arrays  Character Pointers, Arrays and Strings  Examples.

Sum of array using pointer / #include<iostream.h> main() { int sum=0, first_array[3]={ 43,23,54}; int *ptr=& first_array[0]; sum+=*ptr++; sum+=*ptr++; sum+=*ptr++; cout<<"\n sum="<<sum; system("pause"); }

Page 13: Pointers in C++. Topics Covered  Introduction to Pointers  Pointers and arrays  Character Pointers, Arrays and Strings  Examples.

Multi dimetnenal array Int first_array[2][2]={{34,26},{43,23} }; int *ptr=& first_array[0][0]

Page 14: Pointers in C++. Topics Covered  Introduction to Pointers  Pointers and arrays  Character Pointers, Arrays and Strings  Examples.

Multiply by *4 #include<iostream.h> main() { int i, j,first_array[2][2]={{34,26},{43,23} }; int *ptr=& first_array[0][0]; for(i=0;i<2*2;i++) *(ptr+i)=*(ptr+i)*4; for(i=0;i<2 ;i++){ for(j=0;j<2 ;j++) cout<< first_array[i][j]; cout<<"\n";} system("pause");}

Page 15: Pointers in C++. Topics Covered  Introduction to Pointers  Pointers and arrays  Character Pointers, Arrays and Strings  Examples.

Adding using pointer #include<iostream.h> main() { int sum=0, first_array[2][2]={{34,26},

{43,23} }; int *ptr=& first_array[0][0]; sum+=*ptr++; sum+=*ptr++; sum+=*ptr++; sum+=*ptr++; cout<<"\n sum="<<sum;}

Page 16: Pointers in C++. Topics Covered  Introduction to Pointers  Pointers and arrays  Character Pointers, Arrays and Strings  Examples.

Function using pointer(change small to capital letters )

#include<iostream.h> inline toBigLeter (char *ptr) {*ptr=int(*ptr)-32;} main() { char inputchar; cin>> inputchar; toBigLeter (& inputchar ); cout<<"Big to it is="<< inputchar;}

Page 17: Pointers in C++. Topics Covered  Introduction to Pointers  Pointers and arrays  Character Pointers, Arrays and Strings  Examples.

Add anf find average of matrix #include <iostream.h> main( ) {int sizearray,j,sum,avg; sum=0; cout<<"who size the arrray\n" ; cin>> sizearray ; int *Array=new int [ sizearray ]; cout<<"enter the array\n" ; for ( j=0;j<sizearray; j++) cin>> Array[j] ; for (j=0;j<sizearray; j++) sum=sum+Array[j]; avg=sum/sizearray; cout<<"sum="<<sum<<"\navg= "<<avg; system("pause");}

Page 18: Pointers in C++. Topics Covered  Introduction to Pointers  Pointers and arrays  Character Pointers, Arrays and Strings  Examples.

Inter matrix and find diameter #include <iostream.h> void main ( ) { int i,j,k,sum,rowN,colN; sum=0; cin>>rowN>>colN ; int **Array=new int *[ rowN ]; for (k=0 ; k< rowN ; k++) Array[k]=new int[ colN ]; for (i=0 ; i< rowN ; i++) for (j=0; j< colN ; j++) cin>>Array[i][j] ; for (i=0 ; i< rowN ; i++) for (j=0; j< colN ; j++) if (i==j) sum=sum+ Array[i][j]; cout<<"sum="<<sum ;}

Page 19: Pointers in C++. Topics Covered  Introduction to Pointers  Pointers and arrays  Character Pointers, Arrays and Strings  Examples.

Character Pointers, Arrays and Strings How do we initialize a Character pointer?

Initialize it to NULL. char* a = NULL; Let it point to a character array.

char* a; char b[100]; a = b; Initialize to a character string.

char* a = “Hello”; a pointer to the memory location where ‘H’ is stored. Here “a” can be viewed as a character array of size 6, the only difference being that a can be reassigned another memory location.

Page 20: Pointers in C++. Topics Covered  Introduction to Pointers  Pointers and arrays  Character Pointers, Arrays and Strings  Examples.

Examples char* a = “Hello”;

a -> gives address of ‘H’ *a -> gives ‘H’ a[0] -> gives ‘H’ a++ -> gives address of ‘e’ *a++ -> gives ‘e’ a = &b; where b is another char variable is perfectly LEGAL.

However “char a[100];” “a =&b;” where b is another char variable is ILLEGAL.

Page 21: Pointers in C++. Topics Covered  Introduction to Pointers  Pointers and arrays  Character Pointers, Arrays and Strings  Examples.

Pointer in C++

Pointer in C++

Page 22: Pointers in C++. Topics Covered  Introduction to Pointers  Pointers and arrays  Character Pointers, Arrays and Strings  Examples.

Pointer in C++

c = a; // c == 1176 c = *a; // c ==25 b == 25 &b == 1776 a == 1776 *a == 25 *a == b

Page 23: Pointers in C++. Topics Covered  Introduction to Pointers  Pointers and arrays  Character Pointers, Arrays and Strings  Examples.

int * number; char * character; float * greatnumber;

Pointer can be :

// my first pointer #include <iostream> using namespace std;int main (){int a = 5, b = 15;int *ptr;ptr= &a;*ptr = 10;ptr = &b;*ptr = 20;cout<<"a="<<a<<" , b="<<b;return 0;}

Page 24: Pointers in C++. Topics Covered  Introduction to Pointers  Pointers and arrays  Character Pointers, Arrays and Strings  Examples.

more pointers

#include <iostream> using namespace std; int main () { int a = 5, b = 15; int *p1, *p2; p1 = &a; p2 = &b; *p1 = 10; *p2 = *p1; p1 = p2; *p1 = 20; cout << "a=" << a << " , b=" << b; return 0; }

Page 25: Pointers in C++. Topics Covered  Introduction to Pointers  Pointers and arrays  Character Pointers, Arrays and Strings  Examples.

// more pointers

#include <iostream> using namespace std; int main () { int numbers[5]; int * p; p = numbers; *p = 10; p++; *p = 20; p = &numbers[2]; *p = 30; p = numbers + 3; *p = 40; p = numbers; *(p+4) = 50; for (int n=0; n<5; n++) cout << numbers[n] << ", "; return 0; }

Page 26: Pointers in C++. Topics Covered  Introduction to Pointers  Pointers and arrays  Character Pointers, Arrays and Strings  Examples.

Matrix of pointer

char* cars[3]; char[0]="Mercedes"; char[1]="Nissan"; char[2]="Ferrari";

Page 27: Pointers in C++. Topics Covered  Introduction to Pointers  Pointers and arrays  Character Pointers, Arrays and Strings  Examples.

more pointers

char a; char * b; char ** c; a = 'z'; b = &a; c = &b;

Page 28: Pointers in C++. Topics Covered  Introduction to Pointers  Pointers and arrays  Character Pointers, Arrays and Strings  Examples.

// integer increaser sizeof#include <iostream> using namespace std;void increase (void* data, int type){switch (type){case sizeof(char) : (*((char*)data))++; break;case sizeof(short): (*((short*)data))++; break;case sizeof(long) : (*((long*)data))++; break;}}int main (){char a = 5;short b = 9;long c = 12;increase (&a, f(a));increase (&b,sizeof(b));increase (&c,sizeof(c));cout << (int) a << ", " << b << ", " << c;return 0;}

Page 29: Pointers in C++. Topics Covered  Introduction to Pointers  Pointers and arrays  Character Pointers, Arrays and Strings  Examples.

// pointer to functions// pointer to functions#include <iostream> using namespace std;int addition(int a, int b){ return (a+b); }int subtraction(int a, int b){ return (a-b); }int (*minus)(int,int) = subtraction;//pointer to functionint operation(int x, int y, int (*p)(int,int)){int g;g = (*p)(x,y);return (g);} int main (){int m,n;m = operation(7, 5, addition);n = operation(20, m, minus);cout <<n;return 0;}

Page 30: Pointers in C++. Topics Covered  Introduction to Pointers  Pointers and arrays  Character Pointers, Arrays and Strings  Examples.

Example about structures// example about structures#include <iostream> using namespace std;#include <string>struct students{char name[50];char city[50];int tel;}st1,st2;int main(){//filling informationcout<<"enter student1 name, city and tel_no: ";cin>>st1.name;cin>>st1.city;cin>>st1.tel;cout<<"enter student2 name, city and tel_no: ";cin>>st2.name;cin>>st2.city;cin>>st2.tel;//printing informationcout<<"\nname"<<"\tcity\t"<<"tel_no";cout<<"\n------------------------\n";cout<<st1.name<<"\t"<<st1.city<<"\t"<<st1.tel<<endl;cout<<st2.name<<"\t"<<st2.city<<"\t"<<st2.tel<<endl;return 0;}

Page 31: Pointers in C++. Topics Covered  Introduction to Pointers  Pointers and arrays  Character Pointers, Arrays and Strings  Examples.

Print array and summing #include <iostream> using namespace std; int main() { int A[]={5,6,1,9,12,4,7}; int sum=0; for(int i=0;i<7;i++) { cout<<A[i]<<" "; sum+=A[i]; //sum =sum+A[i]; } cout<<"\nsum= "<<sum<<endl; return 0; }

Page 32: Pointers in C++. Topics Covered  Introduction to Pointers  Pointers and arrays  Character Pointers, Arrays and Strings  Examples.

Fibonacci Sequence#include<iostream> using namespace std; // 1  1  2  3  5  8  13  21  34  55  89  144 ......int f[1000]; int fib(int n) {f[0] = 0; f[1] = 1;for(int i=2; i<=n;i++)f[i] = f[i-1]+f[i-2];return f[n];}int main(){int n ;cout<< "Enter n: ";cin>> n;cout<< "\nfib(" << n << ") = " << fib(n) << endl;}