Chapter 5 - Pointers
Chapter 5 - Pointers
Programming with C
1
Pointers
Dr. Firoz Ahmed
Professor
Department of ICE, RU
Chapter Outline
Introduction
Accessing the address of a variable
Declaring pointer variable
Accessing a variable through its pointer
Pointers and arrays
Pointers and character string
Array of pointers
Pointers as function arguments
Pointers to function
Pointers to structure
3
Introduction
A pointer is a derived data types in C
It is build from one of the fundamental data types in C
Pointers contain memory addresses as their values
Since these memory addresses are the locations in the
computer memory where instructions and data are stored
Pointer can be used to access and manipulate data stored in the
memory
Pointers are undoubtedly one of the most distinct and exiting
features of C language
It has added power and flexibility to the language
4
Introduction
Pointers offer a number of benefits to the programmers
Pointers are more efficient in handling arrays and data tables
Pointers can be used to return multiple values from a function via
function arguments
Pointers permit references to functions and thereby facilitating
passing of functions as arguments to other functions
The use of pointer arrays to character strings results in saving of
data storage space in memory
Pointers allow C to support dynamic memory management
Pointer provides an efficient tool for manipulating dynamic data
structure such as structures, link list, queues, stacks and trees
Pointers reduce length and complexity of programs
They increase the execution speed and thus reduce the program
execution time 5
Introduction
Disadvantages of pointers in C
Uninitialized pointers might cause segmentation fault
Dynamically allocated block needs to be freed explicitly.
Otherwise, it would lead to memory leak
Pointers are slower than normal variables
If pointers are updated with incorrect values, it might lead to
memory corruption
6
Introduction
A pointer is a variable whose value is the address of another
variable, i.e., direct address of the memory location
7
Introduction
8
Accessing the address of a variable
The actual address of a variable in the memory is system
dependent and therefore, the address of a variable is not
known to us immediately
How can we then determine the address of a variable?
This can be done with the help of the operator &
We have already seen the use of this address operator in the
scanf function
The operator & immediately preceding a variable returns the
address of the variable associated with it. For example,
p = &quantity;
It would assign the address 5000 to the variable p
The & operator can remembered as ‘address of’
9
Accessing the address of a variable
The & operator can be used only with a simple variable or an
array element
The following are illegal use of address operator
&125 (pointing as constant)
int s[10]; &x (pointing at array names)
&(x+y) (pointing at expression)
If x is an array, then expression such as
&x[10] and &x[i+3];
These are valid and represent the address of 0th and (i+3)th
elements of x
10
Declaring pointer variable
In C, every variable must be declared for its type
Since pointer variables contain addresses that belongs to a
separate data type, it must be declared as pointer before it is
used
The declaration of a pointer variable takes the following form
Data_type *pt_name
This tells the compiler three things about the variable
pt_name
The asterisk(*) tells that the variable pt_name is a pointer variable
Pt_name needs a memory location
Pt_name points to a variable of type data_type
11
Declaring pointer variable
For example
int *p; /*integer pointer*/
It declares the variable p as a pointer variable that points to an
integer data type
Remember that the type int refers to the data type of the
variable being pointed to by p and not the type of the value of
the pointer
Similarly the statement
float *x; /*float pointer*/
It declares x as a pointer to a floating point variable
12
Declaring pointer variable
Pointer variables are declared similarly as normal variable
except for the addition of the unary (*) operator
This symbol can be appear anywhere between the type name
and the variable name
Programmers use the following style
int* P;
int *p;
int * p;
However, the second style is becoming increasingly popular
due to the following reason
It is convenient to have multiple declarations in the same
statement. Example: int *p, x, *q;
13
Initialization of pointer variable
The process of assigning the address of a variable to a pointer
variable is know as initialization
15
Initialization of pointer variable
It must be ensured that the pointer variable always point to
the corresponding types of data
For example
17
Initialization of pointer variable
Pointer are flexible, We can make the same pointer to point to
different data variable in different statements
18
Accessing a variable through its pointer
Once a pointer has been assigned the address of variable
The question is how to access the value of the variable using
the pointer?
Accessing a variable through its pointer we should follow
three steps
At first we define a pointer variable
Secondly, assign the address of a variable to a pointer
Finally, access the value at the address available in the pointer
variable
This is done by using another unary operator *(asterisk),
usually know as indirect operator
19
Accessing a variable through its pointer
Consider the following statements:
20
Accessing a variable through its pointer
21
Accessing a variable through its pointer
22
Pointers and arrays
When an array is declared, the compiler allocates a base
address and sufficient amount of storage to contain all the
elements of the array in contagious memory locations
The base address is the location of the first element (index 0)
of the array
The compiler also defines the array name as a constant
pointer to the first element
Suppose an array x as follows:
Int x[5]={1, 2, 3, 4, 5}
23
Pointers and arrays
Suppose the base address of x is 1000 and assuming that each
integer requires two bytes
The five elements stores as follows:
24
Pointers and arrays
If we declare p as an integer pointer, then we can make the
pointer p to point to the array x by the following statement
p = x; this equivalent to p = &x[0]
Now we can access every value of x using p++ to move from
one element to another
The relationship between x and p is show below:
25
Pointers and arrays
For instance,
26
Pointers and arrays
27
Pointers and arrays
Pointers can be used to manipulate two dimensional arrays as
well
We know that in a one dimensional array x
28
Pointers and arrays
29
Pointers and arrays
The previous figure illustrates how this expression represents
the element a[i][j]
The base address of the array a is &a[0][0] and starting at
this address
The compiler allocates contiguous space for all the element
row-wise
That is, the first element of the second row is placed
immediately after the last element of the first row and so on
30
Pointers and arrays
Suppose we declare an array as follows
32
Pointers and character string
C support an alternative method to create strings using
pointer variable of type char
Example: Char *ptr = str
We can represent the character pointer variable ptr as follows:
33
Pointers and character string
34
Array of pointers
One important use of pointer is in handling of table of strings
Consider the following array of strings
Char name [3][25]
This says that the name is a table containing three names
Each with a maximum length of 25 character
The total storage requirement for the name table are 75 bytes
35
Array of pointers
We know that rarely the individual strings will be of equal
lengths
Therefore instead of making each row a fixed number of
characters
We can make it a pointer to a string of varying length
Like an array of variables, we also use array of pointers in C
An array of pointers is an indexed set of variables, where the
variables are pointers
An array of pointers is useful for the same reason that all
arrays are useful
It allows to numerically index a large set of variables
36
Array of pointers
For example
37
Array of pointers
This declaration allocates only 28 bytes, sufficient to hold all
the character as shown
The following statement would print out all the three names
38
Array of pointers
39
Array of pointers
Difference between pointer to an array and array of pointers
int *a[10];
• Declares and allocates an array of pointers to int
• Each element must be dereferenced individually.
int (*a)[10];
• Declares (without allocating) a pointer to an array of int(s)
• The pointer to the array must be dereferenced to access the value of
each element.
int a[10];
• Declares and allocates an array of int(s).
40
Array of pointers
Pointer to an array:
• Pointer to an array is also known as array pointer
• We are using the pointer to access the components of the array
– int a[3] = {3, 4, 5 };
– int *ptr = a;
• We have a pointer ptr that focuses to the 0th component of the array
• We can likewise declare a pointer that can point to whole array
rather than just a single component of the array
41
Array of pointers
• Syntax:
– data type (*var name)[size of array];
• Declaration of the pointer to an array:
– // pointer to an array of five numbers
– int (* ptr)[5] = NULL;
• The above declaration is the pointer to an array of five integers
• We use parenthesis to pronounce pointer to an array
• Since subscript has higher priority than indirection, it is crucial to
encase the indirection operator and pointer name inside brackets
42
Array of pointers
43
Array of pointers
Array of pointers
• It is an array of the pointer variables
• It is also known as pointer arrays
• Syntax:
– int *var_name[array_size];
• Declaration of an array of pointers:
– int *ptr[3];
• We can make separate pointer variables which can point to the
different values or we can make one integer array of pointers that
can point to all the values
44
Array of pointers
45
Array of pointers
Remember the difference between the notations *p[3] and
(*p)[3]
Since * has a lower precedence than [], *p[3] declares p as an
array of 3 pointers while (*p)[3] declares p as a pointer to an
array of three elements
46
Pointers as function arguments
When an array is passed to a function as an argument, the
actual values of the array elements is not passed
Only the address of the first element of the array is passed
If x is an array, when we call sort(x), the address of x[0] is
passed to the function sort
The function uses this address for manipulating the array
element
Similarly, we can pass the address of a variable as an
argument to a function in the normal fashion
When we pass address to a function, the parameters receiving
the addresses should be pointers
47
Pointers as function arguments
How to declare a function which accepts a pointer as an
argument?
If a function wants to accept an address of an integer variable then
the function declaration will be
• return_type function_name(int*);
– ‘*’ indicates that the argument is an address of a variable not the
value of a variable
Similarly, If a function wants to accept an address of two integer
variable then the function declaration will be,
• return_type function_name(int*,int*);
The process of calling a function using pointer to pass the
addresses of variable is known as “call by reference”
The function which is called by “reference” can changed the value
of the variable used in the call
48
Pointers as function arguments
What will happen to the argument?
Here, we are passing the address of a variable
So, if we change the argument value in the function, it will modify
the actual value of a variable
49
Pointers as function arguments
51
Pointers to function
A function, like a variable, has a type and an address location
in the memory
52
Pointers to function
It is therefore, possible to declare a pointer to a function,
which can then be used as an argument in another function
A pointer to function or function pointer stores the address
of the function
Though it doesn't point to any data. It points to the first
instruction in the function
A pointer to a function is declared as follows
53
Pointers to function
Example
void (*fptr)();
• We must enclose the function pointer variable with (). like (*fptr)
• Where *fptr is a function pointer, capable of referring a function whose
return type is void and also it will not take any argument ()
Similarly, if we want to point a function whose return type is int
and it takes one integer argument i.e. int fun(int); then the
declaration will be
• int (*fptr)(int);
Remember, the statement like int *fptr(int); would declare
fptr as a function returning a pointer to type
54
Pointers to function
We can make a function pointer to point to a specific function
by simple assigning the name of the function to the pointer
For example
It is equivalent to mul(x,y)
55
Pointers to function
56
Pointers to structure
We know that the name of an array stands for the address of
its zeroth element
The same things is true of the names of arrays of structure
variable
Consider the following declaration
59
Pointers to structure
60
Pointers to structure
While using structure pointers, we should take care of the
precedence of operators
The operator ‘’ and ‘.’, and () and [] enjoy the highest
priority among the operators
For example
62
Pointers to structure
Consider the following function: