Programming and Problem Solving

Pointers – Introduction

Pointer :

Pointer is a variable that holds the address of another variable.

Features of Pointers:

  • Pointer save the memory space
  • Execution time with pointer is faster because data is manipulated with the address i.e. direct access to memory location
  • The memory is accessed efficiently with the pointer i.e. dynamically memory is allocated and deallocated
  • Pointers are used with data structure

Pointer declaration, initialization and accessing:

Consider the following statement :

Int qty = 179;

The representation of the variable in memory is as follows

Declaring a pointer:

It means ‘p’ is a pointer variable that holds the address of another integer variable/

Initialization of a pointer:

  • Address operator $$(&)$$ is used to initialize a pointer variable.

Example:  

int qty = 175;

int *p;

p= &qty;

Accessing a variable through its pointer:

  • To access the value of the variable, indirection operator (*) is used.

eg:

‘*’ can be treated as value at address

  • The 2 statements is equivalent to the following stmt

P = $$& $$qty;

n = *p;                 $$longleftrightarrow$$                   n =qty

Program:

main ( )

$$left { right.$$

int x,y

int *p;

clrscr ( );

x= 10;

p = $$&$$x;

y= *p;

printf (‘Value of x = $$%d$$n”, x);

printf (‘x is stored at address $$%un”, &$$x);

printf (‘Value of using pointer =  $$%d$$n”, *p);

printf (‘address of x using pointer = $$%u$$n”, p);

printf (“value of x in y = $$%d$$n”, y);

*p = 25;

printf (“now x = $$%d$$”, x)

getch ( );

$$left. right }$$

Output:

Value of x = 10

x is stored at address = 5000

Value of using  pointer = 10

Address of x using pointer = 5000

Value of x in y = 10

Now x = 25

Arithmetic operations using pointers:

Like any other variables, pointer variables can be used in expressions. For eg. If p1 and p2 are properly declared and initialized then the following statements are valid

a) *p1 + *p2

b) *p1 - *p2

c) *p1 * *p2

d) *p1 / *p2                  Note : There must be a blank space between / and * otherwise it is

e ) p1   +          4

  1. f) p2 - 2
  2. g) p1 - p2    Note: returns the no. of elements in between p1 and p2 i.f. both of them point to same array

h) p1++

i) – – p2

j) sum + = *p2

j) p1 > p2

k) p1 = = p2

l) p1 ! = p2

Note : Comparisons can be used meaningfully in handling arrays and strings

The following statements are invalid

a) p1 + p2

b) p1 * p2

c) p1 / 3

d) p1 / p2

Program:

Output:

Address of a = 1234

Address of b =  5678

a = 12  b= 4

x = 42  y= 9