1 of 10

Pointers

Mr. Santosh N. Nagargoje

2 of 10

Introduction

  • each variable you declare in your program will assign a location in the computer's memory.
  • The value, the variable stores is actually stored in the location assigned.
  • & (reference) operator gives you the address occupied by a variable.
  • used to access the memory and manipulate the address.
  • can assign and de-assign any space in the memory as you wish.

3 of 10

Why Pointers?

  • Accessing array elements
  • Passing arguments to a function when the function needs to modify the original argument
  • Passing arrays and strings to functions
  • Obtaining memory from the system
  • Creating data structures such as linked lists

4 of 10

Pointer Variable

  • variables that points to a specific address in the memory pointed by another variable.
  • Syntax:��

data_type *pointer_variable_name; //declaration

pointer_variable_name = &variable_name; //storing an address of a variable

int *a //pointer to integer

float *b //pointer to float

char *n //pointer to character

Distance *dn //pointer to Distance class

5 of 10

Accessing the variable pointed to

* - dereference operator

// accessing the variable pointed to�#include <iostream>�using namespace std;�int main()�{�int var1 = 11; //two integer variables�int var2 = 22;

int* ptr; //pointer to integers�ptr = &var1; //pointer points to var1�cout << *ptr << endl; //print contents of pointer (11)�ptr = &var2; //pointer points to var2�cout << *ptr << endl; //print contents of pointer (22)�return 0;�}

6 of 10

Pointers and Arrays

  • Arrays are using implicit pointers.
  • Ways to use pointers in arrays

//using index

for(){

* (array_variable_name + index );

}

//using pointer variable

pointer_to_array = array_variable_name;

for(){

* (pointer_to_array ++ );

}

7 of 10

Pointers & Functions

Pass by reference:

Pass by Pointers:

return_type function_name(data_type&); //function prototype

function_name(variable) ; //function call

return_type function_name(data_type& variable){

//function definition

}

return_type function_name(data_type*); //function prototype

function_name(&variable) ; //function call

return_type function_name(data_type* variable){

//function definition

}

8 of 10

Passing Arrays

return_type function_name(data_type *); //prototype

function_name(array_variable); //function call

return_type function_name(data_type* pointer_variable_name){

//function definition

for(){

*pointer_variable_name++;

}

}

9 of 10

Memory Management: new and delete

  • obtains memory from the operating system and returns a pointer to its starting point.
  • pointer = new data_type;
  • Syntax

10 of 10

Memory Management: new and delete

  • returns memory to the operating system.
  • Syntax:

delete[] ptr; //deletes block of data

delete ptr //deletes single data