Pointers in C
Pointers in C
Pointers in C
Outline
1 Pointers
2 Pointer Arithmetic
The type of a pointer depends on the type of the variable it points to.
Every pointer points to some data type.
Sizes of basic data types
sizeof(int) = 4
sizeof(float) = 4
sizeof(double) = 8
A SAMPLE
PROGRAM
#include <stdio.h>
0 int
main()
1
{
2 int n;
3 char c;
4 X c int *ptrn;
c=’X’;
.. n=15;
ptrn=&n;
232 − 1
return 0;
}
Memory Layout (Bytes)
0
1
2 #include <stdio.h>
3
int main()
4 X c
{
char c;
.. int n;
int *ptrn;
20 0 n
c=’X’;
21 0 n=15;
22 0 ptrn=&n;
23 15
return 0;
}
..
232 − 1
Sample program using pointers
ADDRESS OPERATIONS
*pointer
pointer data
& data
POINTER ARITHMETIC
#include <stdio.h>
int main()
{
int *ptr; //increments by sizeof(int) (4 bytes)
long *ptrlng; //increments by sizeof(long) (8 bytes)
ptr++;
ptrlng++;
return 0;
}
POINTER ARITHMETIC - II
Pointers and integers are not interchangeable. (except for 0.) We will
have to treat arithmetic between a pointer and an integer, and
arithmetic between two pointers, separately.
Suppose you have a pointer to a long.
long *ptrlng;
Binary Operations between a pointer and an integer
1 ptrlng+n is valid, if n is an integer. The result is the following
byte address
ptrlng + n*sizeof(long)
and not ptrlng + n.
It advances the pointer by n number of longs.
2 ptrlng-n is similar.
Example of pointer arithmetic
POINTER ARITHMETIC - III
Consider two pointers ptr1 and ptr2 which point to the same type of
data.
<datatype> *ptr1, *ptr2;
1 arr is a pointer to the first element of the array. That is, *arr
2 is the same as arr[0].
3 arr+i is a pointer to arr[i]. (arr+iis equivalent to
arr+i*sizeof(int).)
ARRAYS AND POINTERS
- FIGURE . . . .
40 arr[0] = *arr = *(arr+0)
41
42
43
44 arr[1] = *(arr+1)
45
46
47
48 arr[2] = *(arr+2)
49
50
51
int arr[3]; .. ..
Printing array elements using pointers
Passing Pointers to Functions
printf
printf(‘‘ d’’,n);
printf does not need to change the content of n.
Passing arrays to functions
Passing a pointer to data, instead of passing the value of the data can
be much faster.
This is used to reduce the slowdown due to function calling.
The decision to do this must be taken with care.
ADVANTAGES OF POINTERS IN C