Pointers
Pointers
Pointers
1
4/13/2022
Initialization of Pointer
Declaring a pointer variable
variable
data-type *pointer_name; Pointer Initialization is the process of
Data type of pointer must be same as the assigning address of a variable
variable, which the pointer is pointing. to pointer variable.
void type pointer works with all data types, but Pointer variable contains address of variable of
isn't used oftenly. same data type.
In C language address operator & is used to
determine the address of a variable.
The & (immediately preceding a variable name)
returns the address of the variable associated
with it.
int a = 10 ;
int *ptr ; //pointer declaration
ptr = &a ; //pointer initialization or,
int *ptr = &a ; //initialization and declaration
together
Dereferencing of Pointer
Pointer variable always points to same type of Once a pointer has been assigned the address of a
data. variable. To access the value of variable,
float a; pointer is dereferenced, using the indirection
operator *.
int *ptr;
int a,*p;
ptr = &a; //ERROR, type mismatch
a = 10;
p = &a;
printf(“%d”, *a); // ERROR, invalid indirection
printf("%d",*&a); //this will also print the
value of a. printf(“%x", &a); //this will print
the address of a.
printf("%x", p); //this will also print the
address of a.
printf("%d",*p); //this will print the value of
a.
2
4/13/2022
NULL Pointers
It is always a good practice to assign a NULL int main ()
value to a pointer variable in case you do not {
have exact address to be assigned.
int *ptr = NULL;
This is done at the time of variable declaration.
printf("The value of ptr is : %x\n", ptr );
A pointer that is assigned NULL is called
return 0;
a null pointer.
}
Output:
The value of ptr is 0
Void Pointers
On most of the operating systems, programs are Suppose we have to declare integer pointer,
not permitted to access memory at address 0 character pointer and float pointer then we need
because that memory is reserved by the operating to declare 3 pointer variables.
system. However, the memory address 0 has special Instead of declaring different types of pointer
significance; it signals that the pointer is not variable it is feasible to declare single pointer
intended to point to an accessible memory variable which can act as integer pointer,
location. But by convention, if a pointer character pointer.
contains the null (zero) value, it is assumed to
point to nothing.
if(ptr) /* succeeds if p is not null */
if(!ptr) /* succeeds if p is null */
3
4/13/2022
4
4/13/2022
Decrementing a Pointer
Output: const int MAX = 3;
Address of var[0] = bf882b30 int main ()
Value of var[0] = 10 {
Address of var[1] = bf882b34 int var[] = {10, 100, 200};
Value of var[1] = 100 int i, *ptr;
Address of var[2] = bf882b38 ptr = &var[MAX-1];
Value of var[2] = 200 for ( i = MAX; i > 0; i--)
{
printf("Address of var[%d] = %x\n", i, ptr );
printf("Value of var[%d] = %d\n", i, *ptr );
ptr--;
}
return 0; }
5
4/13/2022
#include<stdio.h> Explanation :
int main() Ptr1 and Ptr2 are two pointers which holds memory
{ address of Float Variable.
float *ptr1=(float *)1000; Ptr2-Ptr1 will gives us number of floating point
numbers that can be stored.
float *ptr2=(float *)2000;
ptr2 - ptr1 = (2000 - 1000) / sizeof(float) =
printf("\nDifference : %d",ptr2-ptr1);
1000 / 4 = 250
return 0;
}
Output :
Difference : 250
6
4/13/2022
Pointer Comparisons
Expression Result Pointers may be compared by using relational
operators, such as ==, <, and >.
Address + Number Address
If p1 and p2 point to variables that are related
Address – Number Address to each other, such as elements of the same
array, then p1 and p2 can be meaningfully
Address – Address Number
compared.
Address + Address Illegal The following program modifies the previous
example one by incrementing the variable pointer
so long as the address to which it points is
either less than or equal to the address of the
last element of the array, which is &var[MAX -
1]:
7
4/13/2022
Pointer to Pointer
Value of var[0] = 10 A pointer to a pointer is a form of multiple
Value of var[1] = 100 indirection, or a chain of pointers.
Value of var[2] = 200 Normally, a pointer contains the address of a
variable.
When we define a pointer to a pointer, the first
pointer contains the address of the second
pointer, which points to the location that
contains the actual value as shown below.
int main ()
{
Value of var = 3000
int var;
Value available at *ptr = 3000
int *ptr;
Value available at **pptr = 3000
int **pptr;
var = 3000;
ptr = &var;
pptr = &ptr;
printf("Value of var = %d\n", var );
printf("Value available at *ptr = %d\n", *ptr );
printf("Value available at **pptr = %d\n",
**pptr);
return 0;
}
8
4/13/2022
9
4/13/2022
Meaning of (*++ptr
(*++ ptr))
Consider the Following Example : Calculation of Answer :
int n = 20 , *ptr ; * ++ptr = *(++ptr ) = *( 3060 ) = Value Stored at
ptr = &n; Location 3060
printf("%d",*++ptr); #include<stdio.h>
Explanation : int main()
‘++’ and ‘*’ both have Equal Precedence {
Associativity is from Right to Left ( Expression int n = 20 , *ptr ;
evaluated from R->L) ptr = &n;
Both are Unary (Operates on single operand ) printf("%d",*++ptr);
So ‘ ++ ‘ is Performed First then ‘ * ‘ return(0);
}
Output :
Garbage Value gets printed
Meaning of (++*ptr
(++*ptr)
) pointer Are ++*ptr
++*ptr and *ptr
*ptr++
++ are same ?
int num = 20 , *ptr ; Step by Step Explanation of : ++*ptr
ptr = # Address of Num : 1000
printf("%d",++*ptr); ++ *ptr =++ *(1000)
Explanation : =++ (Value at address 1000)
‘++’ and ‘*’ both are having equal precedence =++ 10 = 11
and priority. Associativity of these two Step by Step Explanation of : *ptr++
operators is from right to left (Expression
Address of Num : 1000
evaluated from R->L)
*ptr++ = *1000 ++ = Value at address 1000 ++ = 10
Both the operators are Unary so they will only
++ = 10
works on single operand
Dereference operator ‘*’ will get chance for
execution before pre increment operator ‘++’.
10
4/13/2022
11
4/13/2022
12
4/13/2022
Row–
Row –Major Space Allocation
Pointer to 1-
1-D Array
An array name is a constant pointer to the first Here variable arr will give the base address,
element of the array. which is a constant pointer pointing to the
When an array is declared, compiler allocates element, arr[0]. Therefore arr is containing the
sufficient amount of memory to contain all the address of arr[0] i.e 1000.
elements of the array. arr is equal to &arr[0] // by default
Suppose we declare an array arr, We can declare a pointer of type int to point to
int arr[5]={ 1, 2, 3, 4, 5 }; the array arr.
Assuming that the base address of arr is 1000 and int *p;
each integer requires two byte, the five element p = arr; // or
will be stored as follows p = &arr[0]; // both the statements are
equivalent.
Now we can access every element of
array arr using p++ to move from one element to
another.
13
4/13/2022
int i;
int a[5] = {1, 2, 3, 4, 5};
int *p = a; // same as int*p = &a[0]
for (i=0; i<5; i++)
{
printf("%d", *p);
p++;
}
int main ()
{
It is legal to use array names as constant double balance[5] = {1000.0, 2.0, 3.4, 17.0,
pointers, and vice versa. Therefore, *(balance + 50.0};
4) is a legitimate way of accessing the data at double *p;
balance[4]. int i;
Once you store the address of first element in p, p = balance;
you can access array elements using *p, *(p+1), printf( "Array values using pointer\n");
*(p+2) and so on. Below is the example to show
for ( i = 0; i < 5; i++ )
all the concepts discussed above:
{
printf("*(p + %d) : %f\n", i, *(p + i) );
}
14
4/13/2022
Pointer to Multidimensional
Array
A multidimensional array is of form, a[i][j]. b is the address of the 0th row.
As we know now, name of the array gives its base b+1 is the address of the 1st row.
address. In a[i][j], a will give the base address b+i is the address of the ith row.
of this array, even a+0+0 will also give the base
The size of a row is
address, that is the address of a[0][0] element.
c × sizeof(int) = 5 × sizeof(int) = 5 × 4 = 20
Here is the generalized form for using pointer
bytes
with multidimensional arrays.
where c is the number of columns.
Arithmetic of *(b+i
*(b+i))
If b is the address of the 0th row, *b is the 0th If *(b+i) is the address of the 0th element of
row itself. the ith row, *(b+i) + 1 is the address of the 1st
A row may be viewed as an 1-D array, so *b is the element of the ith row.
address of the 0th element of the 0th row. Similarly *(b+i) + j is the address of the jth
Similarly b+i is the address of the ith row, element of the ith row.
*(b+i) is the ith row, so *(b+i) is the address
of the 0th element of the ith row. The difference between b + i and b is 10i
(bytes), but the difference between *(b + i) + j
If *b is the address of the 0th element of the
0th row, *b + 1 is the address of the 1st element and *(b+i) is 2j (bytes).
of the 0th row.
Similarly *b + j is the address of the jth
element of the 0th row.
The difference between b + 1 and b is 10 (bytes)
but the difference between *b + 1 and *b is the
sizeof(int), 2 (bytes).
*(b + i) + j
b is the address of the 0th row,
b+i is the address of the ith row,
*(b+i) is the address of the 0th element of the
ith row,
*(b+i)+j is the address of the jth element of the
ith row,
15
4/13/2022
16
4/13/2022
Array of Pointers
We can also have array of pointers. NOTE: In the second approach memory wastage is
Pointers are very helpful in handling character more, hence it is prefered to use pointer in such
array with rows of varying length. cases.
char *name[3]={ “Baroda”, “Anand”, “Surat” };
Now see same array without using pointer
char name[3][20]= { “Baroda”, “Anand”, “Surat”
};
Pointer to functions
It is possible to declare a pointer pointing to a A function pointer can point to a specific
function which can then be used as an argument in function when it is assigned the name of the
another function. function.
A pointer to a function is declared as follows, int sum(int, int);
type (*pointer-name)(parameter); int (*s)(int, int);
Example : s = sum;
int (*sum)(); //legal declaraction of pointer to s is a pointer to a function sum. Now sum can be
function called using function pointer s with the list of
int *sum(); //This is not a declaraction of parameter.
pointer to function s (10, 20);
17
4/13/2022
Pointer Applications
A. Passing Parameter by Reference B. Accessing Array element
First pointer application is to pass the int main()
variables to function using pass by reference {
scheme.
int a[5] = {1,2,3,4,5};
void swap(int *num1,int *num2)
int *ptr;
{
ptr = a;
int temp;
for(i=0;i<5;i++)
temp = *num1;
{
*num1 = *num2;
printf("%d",*(ptr+i));
*num2 = *num1;
}
}
return(0);
In this scheme we are able to modify value at
}
direct memory location.
18
4/13/2022
Pointer Mistake
E. Some other pointer applications : Mistake 1 : Assigning Value to Pointer Variable
Passing Strings to function int * ptr , m = 100 ;
Provides effective way of implementing ptr = m ; // Error on This Line
the different data structures such as tree, Correction :
graph, linked list ptr is pointer variable which is used to store
the address of the variable.
Pointer Variable “ptr” contain the address of
the variable of type ‘int’ as we have declared
pointer variable with data type ‘int’.
In order to resolve this problem we should assign
address of variable to pointer variable
Write it like this –
ptr = &m ;
19
4/13/2022
Dangling Pointer
Dangling pointers arise when an object is deleted Way 1 : Using free or de-allocating memory
or de-allocated, without modifying the value of #include<stdlib.h>
the pointer, so that the pointer still points to
void main()
the memory location of the de-allocated memory.
{
In short pointer pointing to non-existing memory
location is called dangling pointer. char *ptr = malloc(Constant_Value);
// statements
free (ptr); /* ptr now becomes a dangling pointer
*/
}
We have declared the character pointer in the
first step. After execution of some statements we
have de-allocated memory which is allocated
previously for the pointer.
As soon as memory is de-allocated for pointer,
20