0% found this document useful (0 votes)
5 views

1-Lecture-DSOOP-Pointers

The document provides an overview of pointers in C++, including their declaration, initialization, and usage in programming. It covers concepts such as pointer arithmetic, passing pointers to functions, and the relationship between pointers and arrays. Additionally, it discusses null pointers, pointers to pointers, and the importance of proper pointer management to avoid errors.

Uploaded by

Sajid Ali
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)
5 views

1-Lecture-DSOOP-Pointers

The document provides an overview of pointers in C++, including their declaration, initialization, and usage in programming. It covers concepts such as pointer arithmetic, passing pointers to functions, and the relationship between pointers and arrays. Additionally, it discusses null pointers, pointers to pointers, and the importance of proper pointer management to avoid errors.

Uploaded by

Sajid Ali
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/ 33

EC-204 Data Structures and Object

Oriented Programming

Pointers

Dr Tahir Nawaz
Website: https://www.tahirnawaz.com
Email: tahir.nawaz@ceme.nust.edu.pk
Introduction
• Variables are memory locations that can be accessed by
their corresponding identifiers, i.e. their names. The
program therefore does not need to care about the
physical address of the data in memory; it simply uses
the identifier whenever it needs to refer to the variable.

• Every memory location has a unique address that can be


accessed using the ampersand (&) operator.

• For a C++ program, the memory of a computer is like a


succession of memory cells, each one byte in size, and
each with a unique address.
Introduction (contd.)
• Example:
#include <iostream>

using namespace std;


int main () {
int var1;
float var2;

cout << "Address of var1 variable: ";


cout << &var1 << endl;

cout << "Address of var2 variable: ";


cout << &var2 << endl;

return 0;
}
Declaration of pointers
• A pointer is a variable whose value is the address of
another variable, thereby essentially pointing to the
address of that other variable.

• Like any variable or constant, we need to declare a


pointer before working with it.

• The general declaration of a pointer variable is as


follows:
type *varName;
• type refers to the the data type
• varName is the name of pointer variable
• ‘*’ is the dereference operator
Declaration of pointers (contd.)
• For example:
int *ip; // pointer to an integer
double *dp; // pointer to a double
float *fp; // pointer to a float
char *ch // pointer to character

• Irrespective of the data type (int, float, char, or


otherwise), what a pointer variable contains is always an
address, a long hexadecimal number that represents a
memory address. The difference between pointers of
different data types is the data type of the variable or
constant that the pointer points to.
Declaration of pointers (contd.)
• Example
// my first pointer
#include <iostream>
using namespace std;

int main ()
{
int firstvalue, secondvalue;
int * mypointer;

mypointer = &firstvalue;
*mypointer = 10;
mypointer = &secondvalue;
*mypointer = 20;
cout << "firstvalue is " << firstvalue << '\n';
cout << "secondvalue is " << secondvalue << '\n';
return 0;
}
Declaration of pointers (contd.)
• Example
// more pointers
#include <iostream>
using namespace std;

int main () {
int firstvalue = 5, secondvalue = 15;
int * p1, * p2;

p1 = &firstvalue; // p1 = address of firstvalue


p2 = &secondvalue; // p2 = address of secondvalue
*p1 = 10; // value pointed to by p1 = 10
*p2 = *p1; // value pointed to by p2 = value pointed to by p1
p1 = p2; // p1 = p2 (value of pointer is copied)
*p1 = 20; // value pointed to by p1 = 20

cout << "firstvalue is " << firstvalue << '\n';


cout << "secondvalue is " << secondvalue << '\n';

return 0;
}
Initialization of pointers
• Pointers can be initialized at the point when they are
declared:
int myvar;
int * myptr = &myvar;

• Note that the above code can also written as the


following:
int myvar;
int * myptr;
myptr = &myvar;
Initialization of pointers (contd.)
• Note that, on initialization, a pointer initializes the
address they point to (i.e., myptr), and NOT the value
being pointed (i.e., *myptr). So, the following statement
is not valid:
*myptr = &myvar;

• Pointers can be initialized either to the address of a


variable (such as in the case above), or to the value of
another pointer (or array):
int myvar;
int *foo = &myvar;
int *bar = foo;
Null pointers
• It’s a good practice to assign NULL to a pointer variable
in case we don’t have exact address to be assigned.
This is done at the time of variable declaration. Such a
pointer is called a null pointer.
• Example
//NULL pointer
#include <iostream>

using namespace std;


int main () {
int *ptr = NULL;
cout << "The value of ptr is " << ptr ;

return 0;
}
Null pointers (contd.)
• In order to check for a null pointer, we can do the
following:
if(ptr) // succeeds if p is not null
if(!ptr) // succeeds if p is null

• Thus, if all unused pointers are given the null value and
you avoid the use of a null pointer, you can avoid the
accidental misuse of an uninitialized pointer. Many times,
uninitialized variables hold some junk values and it
becomes difficult to debug the program.
Pointer arithmetic
• Since pointer is an address that is a numeric value, we
can perform arithmetic operations on a pointer just like
it’s done on a numeric value. The four arithmetic
operators we can use on pointers are: ++, --, +, and -
• For example, consider a pointer ptr that is of type int
and lets say it points to the address 1000. Assuming 32-
bit integers, if we do
ptr++;
• ptr will now point to the address 1004 thus pointing to
next integer. Likewise, if ptr points to a character with
an address 1000, then ptr++ will point to the location
1001 because next character will be available at 1001.
Pointer arithmetic (contd.)
• Incrementing a pointer
#include <iostream>

using namespace std;


const int MAX = 3;

int main () {
int var[MAX] = {10, 100, 200};
int *ptr;

// let us have array address in pointer.


ptr = var;

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


cout << "Address of var[" << i << "] = ";
cout << ptr << endl;
Pointer arithmetic (contd.)
• Incrementing a pointer

cout << "Value of var[" << i << "] = ";


cout << *ptr << endl;

// point to the next location


ptr++;
}

return 0;
}
Pointer arithmetic (contd.)
• Decrementing a pointer
#include <iostream>
using namespace std;
const int MAX = 3;

int main () {
int var[MAX] = {10, 100, 200};
int *ptr;

// let us have address of the last element in


pointer.
ptr = &var[MAX-1];

for (int i = MAX-1; i >= 0; i--) {


cout << "Address of var[" << i << "] = ";
cout << ptr << endl;
Pointer arithmetic (contd.)
• Decrementing a pointer

cout << "Value of var[" << i << "] = ";


cout << *ptr << endl;

// point to the previous location


ptr--;
}

return 0;
}
Pointers and Arrays
• The concept of pointers and arrays is actually inter-
related. In fact, arrays work very much like pointers to
their first elements, and, actually, an array can always be
implicitly converted to the pointer of the proper type. For
example, consider these two declarations:
int myarray [20];
int * mypointer;
• The following assignment operation would be valid:
mypointer = myarray;
• But the following is not valid!
myarray = mypointer;
• This is because mypointer can be assigned a different
address, whereas myarray can never be assigned
anything, and will always represent the same block of 20
elements of type int.
Pointers and Arrays
• Example:
#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;
}
Array of pointers
• We can declare an array of pointers as follows:
int *ptr[size];
• The above statement declares an array of int type
pointers, each pointer points to a specific int type
variable
• See the following example:
#include <iostream>

using namespace std;


const int MAX = 3;

int main () {
int var[MAX] = {10, 100, 200};
int *ptr[MAX];
Array of pointers (contd.)
for (int i = 0; i < MAX; i++) {
ptr[i] = &var[i]; // assign the address of
integer.
}

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


cout << "Value of var[" << i << "] = ";
cout << *ptr[i] << endl;
}

return 0;
}
Array of pointers (contd.)
• We can also use an array of pointers to character to
store a list of strings:
#include <iostream>

using namespace std;


const int MAX = 4;

int main () {
const char *names[MAX] = { "Babar Azam", "Muhammad
Rizwan", "Asad Rauf", "Shaheen Afridi" };

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


cout << "Value of names[" << i << "] = ";
cout << (names + i) << endl;
}

return 0;
}
Pointers and constant
• As we have seen that pointers can be used to access a
variable by its address, and this access may include
modifying the value pointed. But it is also possible to
declare pointers that can access the pointed value to
read it, but not to modify it by declaring the pointer as
const.

int x;
int y = 10;
const int * p = &y;
x = *p; // ok: reading p
*p = x; // error: modifying p, which is const-
qualified
Pointer to pointer
• As we know, a pointer contains the address of a variable
it is pointing. When we define a pointer to a pointer, the
first pointer contains the address of the second pointer,
which points to the location that contains the actual value
as shown below.

• A pointer to pointer is declared by placing an additional


asterisk in front of its name.
int **var;
Pointer to pointer (contd.)
• Example:
#include <iostream>

using namespace std;

int main () {
int var;
int *ptr;
int **pptr;

var = 3000;

// take the address of var


ptr = &var;

//take the address of ptr using address of operator &


pptr = &ptr;
Pointer to pointer (contd.)
// take the value using pptr
cout << "Value of var :" << var << endl;
cout << "Value available at *ptr :" << *ptr << endl;
cout << "Value available at **pptr :" << **pptr <<
endl;

return 0;
}
Passing pointers to functions
• Like other variables, we can pass pointers to functions.
This is done by simply declaring the function parameter
as a pointer type.
#include <iostream>
#include <ctime>

using namespace std;


void getSeconds(unsigned long *par);

int main () {
unsigned long sec;
getSeconds( &sec );

// print the actual value


cout << "Number of seconds :" << sec << endl;
return 0;
}
Passing pointers to functions (contd.)
void getSeconds(unsigned long *par) {
// get the current number of seconds
*par = time(NULL);

return;
}
Passing pointers to functions (contd.)
• Example:
#include <iostream>
using namespace std;

// function declaration:
double getAverage(int *arr, int size);

int main () {
// an int array with 5 elements.
int balance[5] = {1000, 2, 3, 17, 50};
double avg;

// pass pointer to the array as an argument.


avg = getAverage( balance, 5 ) ;

// output the returned value


cout << "Average value is: " << avg << endl;
return 0;
}
Passing pointers to functions (contd.)
double getAverage(int *arr, int size) {
int i, sum = 0;
double avg;

for (i = 0; i < size; i++) {


sum += *(arr+i);
}
avg = double(sum) / size;

return avg;
}
Return pointer to functions
• To return a pointer from a function, we declare it as
follows:

int * myFunction();

• Note that it is not good idea to return the address of a


local variable to outside of the function

• So normally we need to define that local variable


as static variable.
Return pointer to functions (contd.)
• Example
#include <iostream>

using namespace std;

// function to input an array and return its elements


int * getArray( ) {
static int r[10];

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


cout << "Enter the value for r[" << i << "]: "
;
cin >> r[i] ;
}

return r;
}
Return pointer to functions (contd.)
// main function to call above defined function.
int main () {
// a pointer to an int.
int *p;

p = getArray();
for ( int i = 0; i < 10; i++ ) {
cout << "*(p + " << i << ") : ";
cout << *(p + i) << endl;
}

return 0;
}
Acknowledgement/References
• https://www.tutorialspoint.com/cplusplus/index.htm

• https://www.cplusplus.com/

• Deital and Deital, “C++ How to Program”, Latest Edition

• Stroustrup, “Programming – Principles and Practice


Using C++”, Latest Edition

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy