0% found this document useful (0 votes)
14 views16 pages

C++ Pointers

Uploaded by

alswyah17
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views16 pages

C++ Pointers

Uploaded by

alswyah17
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

FACULTY OF ELECTONICS TECHNOLOGY

Subject: CP II SEMESTER 4th


Pointers in C++

Accessing address of a variable


Computer‟s memory is organized as a linear collection of bytes. Every byte
in the computer‟s memory has an address. Each variable in program is stored at a
unique address. We can use address operator & to get address of a variable:
Before discussing how pointers work, let us make the following observations.
The statement:
int *p;
is equivalent to the statement:
int* p;
which is equivalent to the statement:
int*p;
Thus, the character * can appear anywhere between the data type name and the
variable name. Now, consider the following statement:
int* p, q;
In this statement, only p is the pointer variable, not q. Here, q is an int
variable. To avoid confusion, we prefer to attach the character * to the variable
name. So the preceding statement is written as:
int *p, q;
Of course, the statement:
int *p, *q;
declares both p and q to be pointer variables of type int.
Now that you know how to declare pointers, next we will discuss how to make a
pointer point to a memory space and how to manipulate the data stored in
these memory locations.
Because the value of a pointer is a memory address, a pointer can store the
address of a memory space of the designated type. For example, if p is a pointer
of type int, p can store the address of any memory space of type int. C++
provides
two operators—the address of operator (&) and the dereferencing operator (*)—to
work with pointers.

Eng:Alhadi 1
FACULTY OF ELECTONICS TECHNOLOGY
Subject: CP II SEMESTER 4th
Pointers in C++

4
Address of Operator (&):- 1
In C++, the ampersand, &, called the address of operator, is a unary operator
that the statement:
p = &x;
assigns the address of x to p. That is, x and the value of p refer to the same
memory location.

//program determine the address of two variabls


#include <iostream>
using namespace std;
int main ()
{int var1;
char var2[10];
cout << "Address of var1 variable: ";
cout << &var1 << endl;
cout << "Address of var2 variable: ";
cout << &var2 << endl;
system("PAUSE");
return 0;
}
Dereferencing Operator (*):-
C + + used the asterisk character, *, as the binary multiplication operator. C++
also uses * as a unary operator. When used as a unary operator, *, commonly referred
to as the dereferencing operator or indirection operator, refers to the object to
which its operand (that is, the pointer) points. For example, given the statements:
int x = 25;
int *p;
p = &x;//store the address of x in p
the statement:

Eng:Alhadi 2
FACULTY OF ELECTONICS TECHNOLOGY
Subject: CP II SEMESTER 4th
Pointers in C++

cout << *p << endl;


prints the value stored in the memory space pointed to by p, which is the value of x.
Also, the statement:
*p = 55; stores 55 in the memory location pointed to by p—that is, in x.
Let us consider the following statements:
int *p;
int num;
In these statements, p is a pointer variable of type int, and num is a variable of
type int. Let us assume that memory location 1200 is allocated for p, and
memory location 1800 is allocated for num. (See Figure 1 shown below).
. . . . . . . . .
1200 1800
P num
returns the address of its operand. For example, given the statements:
int x;
int *p;
Consider the following statements.
1. num = 78;
2. p = &num;
3. *p = 24;
The following shows the values of the variables after the execution of each
statement.

Eng:Alhadi 3
FACULTY OF ELECTONICS TECHNOLOGY
Subject: CP II SEMESTER 4th
Pointers in C++

int num = 23;


cout << &num; // prints address in hexadecimal
complete example
#include <iostream>
#include <stdlib.h>
using namespace std;
int main()
{int num = 23;
cout << &num<<endl; // prints address in hexadecimal
system("PAUSE");
return 0;
}

POINTER
A pointer is a variable that holds a memory address, usually the location of

Eng:Alhadi 4
FACULTY OF ELECTONICS TECHNOLOGY
Subject: CP II SEMESTER 4th
Pointers in C++

another variable in memory.

int *ip; // pointer to an integer


double *dp; // pointer to a double
float *fp; // pointer to a float
char *ch // pointer to character

Defining a Pointer Variable


int *iptr;
iptr can hold the address of an int

Pointer Variables Assignment:


int num = 25;
int *iptr;
iptr = &num; num iptr
25 0x4a00
address of num 0x4a00

Null Pointers
It is always a good practice to assign the pointer NULL to a pointer variable
in case you do not have exact address to be assigned. This is done at the time of
variable declaration. A pointer that is assigned NULL is called a null pointer.
The NULL pointer is a constant with a value of zero defined in several
standard libraries, including iostream. Consider the following program:
#include <iostream>
using namespace std;
int main ()
{
int *ptr = NULL;
Eng:Alhadi 5
FACULTY OF ELECTONICS TECHNOLOGY
Subject: CP II SEMESTER 4th
Pointers in C++

cout << "The value of ptr is " << ptr <<endl;


system("pause");
return 0;
}

Memory layout
To access num using iptr and indirection operator *
cout << iptr; //
prints0x4a00 cout << *itptr;//
prints 25

Similary, following declaration shows:


char *cptr;
float *fptr;
cptr is a pointer to character and fptr is a pointer to float value.
A Pointer to a Pointer
Instead of pointing to a regular variable, a pointer can be made to point to another
pointer. To apply this, always remember that you must specify what target a
pointer is pointing to. Once again, consider the following example:

#include <iostream>
using namespace std;
int main()
{ int value = 26;
int *pointer;
pointer = &value;
cout << " Value = " << value << "\n";

Eng:Alhadi 6
FACULTY OF ELECTONICS TECHNOLOGY
Subject: CP II SEMESTER 4th
Pointers in C++

cout << "*Pointer = " << *pointer << "\n";


system("pause");
return 0;
}
In this program, if necessary, you can declare a new variable that is a pointer that itself
points to another pointer. When declaring such a variable, precede it with two *. After
declaring the pointer, before using it, you must initialize it with a reference to a pointer,
that is, a reference to a variable that was declared as a pointer. Here is an example:
#include <iostream>
using namespace std;
int main()
{ int value = 26;
int *pointer;
int **pointerToPointer;
pointer = &value;
pointerToPointer = &pointer;
cout << " Value = " << value << "\n";
cout << " *Pointer = " << *pointer << "\n";
cout << "**Pointer = " << **pointerToPointer << "\n";
system("pause");
return 0;

Just as demonstrated earlier, after initializing a pointer, if you change the value of the
variable it points to, the pointer would be updated. Consider the following program:
#include <iostream>
using namespace std;
int main()
{ int value = 26;
int *pointer;
int **pointerToPointer;
pointer = &value;
pointerToPointer = &pointer;

Eng:Alhadi 7
FACULTY OF ELECTONICS TECHNOLOGY
Subject: CP II SEMESTER 4th
Pointers in C++

cout << " Value = " << value << "\n";


cout << " *Pointer = " << *pointer << "\n";
cout << "**Pointer = " << **pointerToPointer << "\n";
value = 4805;
cout << "After changing the value of the main variable...\n";
cout << " Value = " << value << "\n";
cout << " *Pointer = " << *pointer << "\n";
cout << "**Pointer = " << **pointerToPointer << "\n";
system("PAUSE");
return 0;
}

Pointer Arithmetic
Some arithmetic operators can be used with pointers:
- Increment and decrement operators ++, --
-Integer can be added to or subtracted from pointers using the pointers
using the operaters +,-,+=,and -=

Each time a pointer is incremented by 1, it points to the memory location of the


next element of its base type.
If “p” is a character pointer then “p++” will increment “p” by 1 byte.
If “p” were an integer pointer its value on “p++” would be incremented by 4
bytes.
Pointers and Arrays
Array name is base address of array
int vals[] = {4, 7, 11};
cout << vals; // displays 0x4a00
cout << vals[0]; // displays 4
Lets takes an example:
int arr[]={4,7,11};
int *ptr = arr;

Eng:Alhadi 8
FACULTY OF ELECTONICS TECHNOLOGY
Subject: CP II SEMESTER 4th
Pointers in C++

What is ptr+1?
It means (address in ptr) + (1 * size of an int)
cout<<*(ptr+1);// display 7
cout<<*(ptr+2);// display 11

Example :here complete code for float array and access to it’s elements by
pointer
#include <iostream>
#include <stdlib.h>

using namespace std;

int main()
{float arr[]={30.5,44.7,65.7,88.9,90.2,77.9,69.69};
float *ptr = arr;
cout<<*(ptr)<<endl;// display
cout<<*(ptr+2)<<"\n";// display 3th array element
cout<<*(ptr+6)<<"\n";// display 7th array element
system("PAUSE");
return 0;
}

Example :complete code for insert integer array have eight elements ,print out
the elements ,print out the elements using pointer and display the memory
address for each array elements.
//program to Array Access & print out the array elments using pointers
// print out each array element address
#include <iostream>
#include <stdlib.h>
using namespace std;
int main()
{int vls[8];
int *ptr1 = vls;
cout<<" insert eight array elements"<<endl;
for(int i=0;i<8;i++){
cout<<"a["<<i<<"] = ";
cin>>vls[i];}

Eng:Alhadi 9
FACULTY OF ELECTONICS TECHNOLOGY
Subject: CP II SEMESTER 4th
Pointers in C++

cout<<"\n display the values of array elements "<<"\n";


for(int i=0;i<8;i++)
cout<<" vls["<<i<<"] = "<<vls[i]<<" ";
cout<<"\n\n";

cout<<"\t\t display array element by pointer "<<endl;


for(int i=0;i<8;i++)
cout<<" vls["<<i<<"] = "<<*ptr1++<<" ";
cout<<"\n\n";
cout<<"\t\t Display the array element addresses "<<endl;
for(int i=0;i<8;i++)
cout<<" vls["<<i<<"] = "<<ptr1++<<" ";
system("PAUSE");
return 0;
}

Array Access
Array notation arr[i] is equivalent to the pointer notation *(arr + i)
Assume the variable definitions
int arr[]={4,7,11};
int *ptr = arr;
Examples of use of ++ and -- ptr++; // points at 7

ptr--; // now points at 4

Example Decrementing a Pointer Thesame considerations apply to decrementing a


pointer, which decreases its value by the number of bytes of its data type as
shown below:
//program using decrment operator for pointer to access array elements and print
out each element address
#include <iostream>
using namespace std;
const int MAX = 3;
int main ()
{int var[MAX] = {10, 100, 200};

Eng:Alhadi 10
FACULTY OF ELECTONICS TECHNOLOGY
Subject: CP II SEMESTER 4th
Pointers in C++

int *ptr=var;
// let us have address of the last element in pointer. ptr = &var[MAX-1];
for (int i = MAX; i > 0; i--)
{cout << "Address of var[" << i << "] = ";
cout << (ptr-(i-1)) << endl;
cout << "Value of var[" << i << "] = ";
cout << *(ptr+i-1) << endl;// point to the previous location ptr--;
cout<<endl;
}
system("PAUSE");
return 0;
}
After execute the program result will be

Character Pointers and Strings


Initialize to a character string.
char* a = “Hello”;
a is 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.
char* a = “Hello”;
a gives address of „H‟
*a gives „H‟

Eng:Alhadi 11
FACULTY OF ELECTONICS TECHNOLOGY
Subject: CP II SEMESTER 4th
Pointers in C++

a[0] gives „H‟


a++ gives address of „e‟
*a++ gives „e‟
Here complete code
#include <iostream>
#include <stdlib.h>
using namespace std;
int main()
{char* a="Hello";
cout<< a[0]<<"\n\n";
cout<<*a++<<endl;
cout<<a[2]<<endl;
cout<<a[0]<<a[1]<<endl;
system("PAUSE");
return 0;
}
Example Access to the string using pointer and print out.
// printing the string using pointer
#include <iostream>
#include <stdlib.h>
using namespace std;
int main()
{char* a="Hello";
for(int i=0;i<5;i++)
cout<<*(a+i)<<" ";
cout<<endl;
system("PAUSE");
return 0;
}

Pointers as Function Parameters


A pointer can be a parameter. It works like a reference parameter to allow
change to argument from within function

Eng:Alhadi 12
FACULTY OF ELECTONICS TECHNOLOGY
Subject: CP II SEMESTER 4th
Pointers in C++

#include<iostream>
using namespace std;
void swap(int *, int *);
int main()
{int a=10,b=20;
cout<< "value of a and b before sawpping a="<<a<<" b= "<<b<<endl;
swap(&a, &b); // calling swap function
cout<< "value of a and b after sawpping a="<<a<<" b= "<<b<<endl;
system("pause");
return 0;
}
void swap(int *x, int *y)
{
int t;
t=*x;
*x=*y;
*y=t;
}
Pointers to Constants and Constant Pointers
Pointer to a constant: cannot change the value that is pointed at Constant
pointer: address in pointer cannot change once pointer is initialized
Pointers to Structures
We can create pointer to structure variables
struct student{ int rollno;float fees;};
student *stuptr=&stu1;
(*stuptr).rollno=104;
Static allocation of memory
In the static memory allocation, the amount of memory to be allocated is
predicted and preknown. This memory is allocated during the compilation
itself.
All the declared variables declared normally, are allocated memory statically.

Dynamic allocation of memory

Eng:Alhadi 13
FACULTY OF ELECTONICS TECHNOLOGY
Subject: CP II SEMESTER 4th
Pointers in C++

In the dynamic memory allocation, the amount of memory to be allocated is


not known. This memory is allocated during run-time as and when required.
The
memory is dynamically allocated using new operator.
Free store
Free store is a pool of unallocated heap memory given to a program that is
used by the program for dynamic allocation during execution.
Dynamic Memory Allocation
We can allocate storage for a variable while program is running by using new
operator

To allocate memory of type integer


int *iptr=new int;
To allocate array
double *dptr = new double[25];
To allocate dynamic structure variables or objects
Student sptr = new Student; //Student is tag name of structure
Releasing Dynamic Memory
Use delete to free dynamic memory
delete iptr;
To free dynamic array memory
delete [] dptr;
To free dynamic structure
delete Student;

Memory Leak
If the objects, that are allocated memory dynamically, are not deleted using
delete, the memory block remains occupied even at the end of the program.
Such memory blocks are known as orphaned memory blocks. These orphaned
memory blocks when increase in number, bring adverse effect on the system.
This situation is called memory leak
*After using a pointer, don't forget to clean your memory. You do this using the
delete operator

Eng:Alhadi 14
FACULTY OF ELECTONICS TECHNOLOGY
Subject: CP II SEMESTER 4th
Pointers in C++

Few important pointer concepts


Concept Description
C++ Null Pointers C++ supports null pointer, which is a constant with avalue of
zero defined in several standard libraries.
C++ pointer arithmetic There are four arithmetic operators that can be used on
pointers: ++, --, +, -
C++ pointers vs arrays There is a close relationship between pointers and array.
C++ array of pointers You can define arrays to hold a number of pointers.
C++ pointer to pointer C++ allows you to have pointer on a pointer and so on.
Passing pointers to functions Passing an argument by reference or by address both
enable the passed argument to be changed in the
calling function by the called function.
Assignment :-
Q1-write program to inilize array like marks[]={65.7,78.8,77.0,6.5,90.4,67.8}
Using pointer to access array print
1-the first element of array and it’s memory address.
2.the 5th element.
Q2- suppose you have declare
float arr[]={4.5,7.9,60.8};
float *ptr = arr;
write statement for deleting the pointer?
Q3 suppose you have char* name={Ahmed Ali Fathi Alwerfli};
Using increment and decrement operaters with pointer write program to
I. display First name.
II. display Fathi.

Q3 How to clean memory after using pointers?


Q4 write program using Pointers as Function Parameters to find
1. Add two integer numbers a,b

Eng:Alhadi 15
FACULTY OF ELECTONICS TECHNOLOGY
Subject: CP II SEMESTER 4th
Pointers in C++

2. The average of *x0 =100.60,*y0=40.60,*z0 =33.70


3. Divide *x0/*y0

Eng:Alhadi 16

You might also like