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

Preview:

Citation preview

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.

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

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;

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.

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>

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"); }

Change value of pointer

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

#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");

}

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"); }

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"); }

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

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");}

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

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

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");}

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

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.

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.

Pointer in C++

Pointer in C++

Pointer in C++

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

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

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

// 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; }

Matrix of pointer

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

more pointers

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

// 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;}

// 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;}

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

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

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

Recommended