Pointers

  • Declaring pointers
  • The “&“ operator
  • The “*“ operator
  • Initialising pointers
  • Type mismatches
  • Call by reference
  • Pointers to pointers

 

Pointers - Why?


Using pointers allows us to:
— Achieve call by reference (i.e. write functions which change their parameters)
— Handle arrays efficiently
— Handle structures (records) efficiently
— Create linked lists, trees, graphs etc.
— Put data onto the heap
— Create tables of functions for handling Windows events, signals etc.
Already been using pointers with scanf
Care must be taken when using pointers since there are no safety features

 

Declaring Pointers

  • Pointers are declared by using “*”


Declare an integer:

1
int i;

 

Declare a pointer to an integer:

1
int *p;

 

There is some debate as to the best position of the "*":

1
int* p;

 

 

Examples Pointer Declaration:

1
2
3
4
5
6
7
int *pi;	 /* pi is a pointer to an int */
long int *p;     /* p is a pointer to a long int */		
float* pf;	 /* pf is a pointer to a float */
char c, d, *pc;	 /* c and d are char pc is a pointer to char */
double* pd, e, f;/* pd is a pointer to a double, e and f are double */
char* start;	 /* start is a pointer to a char */
char* end;	 /* end is a pointer to an int */

 

 

The “&“ Operator

  • The “&“, “address of” operator, generates the address of a variable
  • All variables have addresses except register variables

Example :

1
2
3
4
5
6
7
8
9
10
char g = 'z';
int main(void)
{ 
  char c = 'a';
  char *p;
  
  p = &c;
  p = &g;
  return 0;
}

 

Result :

1
2
3
p: 0x1132-------->c:'a'
 
p: 0x91A2-------->g:'z'

 

 

The “*“ Operator

  • The “*“, “points to” operator, finds the value at the end of a pointer
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <stdio.h>
 
char g = 'z';
int main(void)
{
  char c = 'a';
  char *p;
  
  p = &c;
  printf("%c\n", *p);
  
  p = &g;
  printf("%c\n", *p);
  
  return 0;
}

 

 Result :

1
2
3
p: 0x1132-------->c:'a'
 
p: 0x91A2-------->g:'z'

 

Here, result will be printed  "what "p point to"