Unit 11
Pointers
The pointer in C language is a variable which stores the address of another variable. This variable can be of type int, char, array, function, or any other pointer. ... Int n = 10; int* p = &n; // Variable p of type pointer is pointing to the address of the variable n of type integer.
One of the vital and heavily used feature ‘C’ is pointer. Most of the other programming languages also support pointers but only few of them use it freely. Support pointers but only few of them use it freely.
When we declare any variable in C language, there are three things associated with that variable.
1. Data type of variable : Data type defines the type of data that variable can hold. Data type tells compiler about the amount of memory allocate to the variable.
2. Address of Variable : Address of variable represent the exact address of memory location which is allocated to variable.
3. Value of variable : It is the value of variable which is store at the address of memory location allocated to variable.
Example : int n = 5;
In the above example ‘int’ is the data type which tells compiler to allocate 2 bytes of memory to variable ‘n’.
Once the variable is declare compiler allocated two bytes of memory to variable ‘n’. Suppose the address of that memory location is 1020. At the address of memory location 1020 the value 5 is store.
Memory map for above declaration is as follows.
Use of &,/and ‘*’ operator
Consider the following program.
#include<stdio.h>
#include<conio.h>
Void main()
{
Int a,b,c,
Printf (“Enter two numbers”);
Scanf (“%d%d”, & a,&b);
c=a+b;
Printf(“/n Addition is %d”, C);
Printf(“/n Address of variable C is %d”, &C);
Getch ();
}
Above program is the program for addition of two numbers in ‘C’ language. In the sevent instruction of above program we used operator ‘%’ and ‘&’ ‘%d’ is the access specifier which tells compiler to take integer value as a inpute whereas. ‘&a’ tells compile to store the taken value at the address of variable ‘a’.
In the ninth instruction compiler will print me value of ‘C’ so the output of 9th instruction is as follows.
Addition is 5 [Note : considering a = 2 and b = 3]
In the tenth instruction compiler will print me address of variable C.
So the output of lenth instruction is as follows. Address of variable C is 1020.
Now consider the following program.
#include<stdio.h>
#include<conio.h>
Void main()
{
Int a,b,c;
Printf(“Enter two numbers”);
Scanf(“%d %d”, & a, &b);
c=a+b;
Printf(“\n Addition is %d”,C);
Printf(“\n Address of variable C is %d”,&C);
Printf(‘\n value of variable C is %d”, *(&C));
Getch();
}
Now, we all are clear about the output of instruction 9 and 10.
In the 11th instruction, operator *and & is used. ‘*’ operator tells compile to pickup the value which is stored at the address of variable C. So the output of 11th instruction is as follow. Value of variable C is 5 [considering a = 24 b = 3;]
Pointer is a special variable that can hold the address of another variable whereas arrays are the special type of linear data structure in which elements are stored in contiguous memory locations. Pointers to array are used to retrieve the values of array element from their location. Pointer to array means that a variable which is meant to hold the address of array element. Following is the syntax of assigning the address of array element to pointer.
Pointer-name = & array-name[element];
For example:
Int arr[4];
Int *p;
p= &arr[1];
In the above example, pointer variable ‘p’ is pointing the address of second variable of the array ‘arr’. Following figure depict the pictorial representation of above code.
Declaring Pointer to array
User can access the elements of array by using pointer variable. If we want to store value 7 at the second position then we need to write
*p= 7;
Assigning value to second position of an array
Pointer arithmetic can be used to perform the arithmetic operation on pointer to array. There are three forms of pointer arithmetic
1.Adding an integer to a pointer: C language allows user to add integer value to the pointer variable. Suppose in the above example we can shift the pointer variable ‘p’ to the forth position by writing
p=p+2;
Now, if we write *p=9 then value ‘9’ is stored at the last position.
Adding an integer to a pointer
2.Subtracting an integer from a pointer: Similar to addition of integer to pointer, user can subtract the integer value from pointer variable. We can shift the pointer variable ‘p’ to the third position by writing
p=p-1;
Now, if we write *p=5 then value ‘5’ is stored at the third position
Subtracting an integer from a pointer
3.Subtracting one pointer from another: C language allow user to perform arithmetic operation on two pointer variables. Consider the following code
Int *p,*q, r,s;
Int arr[4];
Arr[1]=7;
Arr[2]=5;
Arr[3]=9;
p=&arr[2];
q=&arr[3];
r= p-q;
s=q-p;
In the above program variable ‘r’ contains the value ‘-1’ whereas variable ‘s’ contain value ’1’.
Pointer to Single Dimensional Arrays
Single dimensional array are the data structure in which all the elements are stored in a single row. Indexing of single dimensional array starts with 0 whereas last element has index (array size-1). All the elements of the array are of similar data-types, C language does not allow user to store elements of two or more different data type in a single array. Suppose user wants to store string ‘Hello Raushan’ then initially user required character type of array. Minimum size of an array to store above string is 13 as it contains 12 alphabets and one space. A pointer variable can store the address of only one array variable at a single instant of time. Similar to array, pointer can also hold the address of only respective type of element. For the above string user required character type of pointer. Following is the syntax of declaring single dimensional array and a pointer to array.
Char arr[13]= {‘H’, ‘e’, ‘l’, ‘l’, ‘o’, ‘ ’, ‘R’, ‘a’, ‘u’, ‘s’, ‘h’, ‘a’, ‘n’};
Char *p;
p=&arr[0];
In the above syntax, First line represents the syntax of declaring and defining single dimensional array. Here we declare the character type of array of size 13. Total memory allocated to the ‘arr’ array is 13. This array can hold 13 elements having data type ‘char’ and all these elements are stored in the consecutive memory location. Here we are storing string ‘Hello Raushan’ to the array ‘arr’. The index of first element (ie ‘H’) is arr[0] where as the last element (ie ‘n’) is having index arr[12].
Second line represents the syntax of declaring pointer variable. Here, we define ‘p’ as a pointer variable which is of type ‘char’. This pointer variable can perform the operation on element having data type ‘char’.
Third line represents the syntax of defining pointer variable. Here, we assign the address of first element of the array ‘arr’ to pointer variable ‘p’.
Memory map of above syntax is as follows
Consider the following basic program of pointer to array
#include<stdio.h>
Void main()
{
Int a[]={1,2,3,5,6,7,8};
Int *p= a;
Printf("\n This is the address of a %u, value of &a is %u ,Address of first element %d ,
Value stored at first place is %d",a,&a,&a[0],*a);
Printf("\nThis is the address at p %u , value at p %u and the value pointed by p
%d",&p,p,*p);
Printf("\n");
}
Output:
This is the address of a 3219815716, value of &a is 3219815716, Address of first element 3219815716 , Value stored at first place is 1
This is the address at p 3219815712, value at p 3219815716 and the value pointed by
p 1
Consider the following program
#include<stdio.h>
#include<conio.h>
Void main()
{
Int arr[3];
Int *p;
Arr[0]=3;
Arr[1]=6;
Arr[2]=8;
For(i=0;i<3;i++)
{
p= &arr[i];
Printf(“address of %d element is”,p);
Printf(“\t value of %d element is \n”,*p);
}
In the above program, we define the array of size 3 in which value of first element of the array is 3, second element has value 6 and last element has value 8.Integer type of pointer variable ‘p’ initially points to the first element of the array. So, first ‘printf’ statement is responsible to print the address of array element whereas second ‘printf’ statement is used to print the value of array element using pointer.
For the first iteration of ‘for’ loop, value of loop variable ‘I’ is ‘0’. So, pointer variable ‘p’ contains the address of first element of the array ‘arr’. First ‘printf’ statement will print the memory address of first element of the array and second ‘printf’ statement print the value of first element of the array ie ‘3’.
In the second iteration loop variable is incremented by one. Now, ‘p’ contains the address of second element of the array ie ‘arr[1]’. So, this time ‘printf’ statements prints the address and value of second element of the array.
In the third iteration loop variable is incremented by one and it becomes ‘2’. Now, ‘p’ contains the address of third element of the array ie ‘arr[2]’. So, this time ‘printf’ statements prints the address and value of third element of the array.
Again the value of loop variable is incremented by one and it becomes ‘3’. So, the condition inside ‘for’ loop is not satisfied and flow of program execution comes out of loop.
Pointer to Multidimensional Arrays
In multidimensional array all the elements of the array are stored in multiple stacks of rows. Two dimensional array has two stacks of rows, it looks like two dimensional matrix containing rows and columns. Three dimensional array has three stacks of rows and it looks like a rubik’s cube. Like single dimensional array, all the elements of multidimensional array are of same type and C language does not allow user to store elements of two or more different data type in a single multidimensional array.
Suppose user wants to store string ‘Hello Raushan’ in two dimensional array, minimum size of an array to store above strings is 13 as it contains 12 alphabets and one space. Two dimensional arrays are built with rows and columns. For the above string we need to divide total array size into rows and columns. A pointer variable can store the address of only one array variable at a single instant of time. Similar to array, pointer can also hold the address of only respective type of element. For the above string user required character type of pointer. Following is the syntax of declaring two dimensional array and a pointer to array.
Char arr[2][7]= {‘H’, ‘e’, ‘l’, ‘l’, ‘o’, ‘ ’, ‘R’, ‘a’, ‘u’, ‘s’, ‘h’, ‘a’, ‘n’};
Char *p;
p=&arr[0][0];
In the above syntax, First line represents the syntax of declaring and defining two dimensional array. Here we declare the character type of array of size 14, which is divided into two rows and seven columns. Total memory allocated to the ‘arr’ array is 14. This array can hold 14 elements having data type ‘char’ and all these elements are stored in the consecutive memory location. Out of 14 elements the first 7 elements are stored in the first row whereas remaining elements are stored in the second row. The index of first element (ie ‘H’) is arr[0][0] where as the last element (ie ‘n’) is having index arr[1][5]. At the last position of the array ie arr[1][6] contains garbage value.
Second line represents the syntax of declaring pointer variable. Here, we define ‘p’ as a pointer variable which is of type ‘char’. This pointer variable can perform the operation on element having data type ‘char’.
Third line represents the syntax of defining pointer variable. Here, we assign the address of first element of the array ‘arr’ to pointer variable ‘p’.
Memory map of above syntax is as follows
Consider the following program
#include<stdio.h>
#include<conio.h>
Void main()
{
Int arr[2][3],i,j,*p;
Clrscr();
Printf("enter the elements of array");
For(i=0;i<2;i++)
{
For(j=0;j<3;j++)
{
Scanf("%d",&arr[i][j]);
}
}
Printf("Two dimensional array is\n");
For(i=0;i<2;i++)
{
For(j=0;j<3;j++)
{
Printf("\t %d",arr[i][j]);
}
Printf("\n");
}
For(i=0;i<2;i++)
{
For(j=0;j<3;j++)
{
p=&arr[i][j];
Printf("\n address is %d and value is %d",p,*p);
}
}
Getch();
}
Output:
Enter the elements of array
4
5
6
1
2
3
Two dimensional array is
4 5 6
1 2 3
Address is -24 and value is 4
Address is -22 and value is 5
Address is -20 and value is 6
Address is -18 and value is 1
Address is -16 and value is 2
Address is -14 and value is 3
In the above program, we define the array of size 6 which is divided in to two rows and three columns. in which value of first element of the array is 4 which is stored at location of arr[0][0], second element has value 4, which is stored at location of arr[0][1]and last element has value 3, which is stored at location of arr[1][2].
In ‘C’ language we can store string in the array of character. Array of character holding string is terminated by null character (‘\0’). C language treats ‘’\0’’ as a one character. ‘\0’ represents the end og the string and also return logical false value. Each element in the array of character requires one byte of memory storage. User can define string constant by putting all the characters of string in a pain of double quotes. C compiler automatically adds ‘\0’ at the end of every string. There are two ways to initialize the string
1. Initialize the string by using array
Char array_name[size]={‘a1’, ‘a2’,…..’an’, ‘\0’};
Example: char arr[7]={‘H’, ’e’, ‘l’, ’l’, ’o’, ‘\0’};
2. Initialize the string constant by using array
Char array_name[size]=”string”;
Example: char arr[7]=”Hello”
In the above syntax, ’C’ compiler automatically introduce ‘\0’ at the end of the string. Array size is not the compulsory factor in the string initialization. User is free to define unsized character array. In unsized character array compiler will calculate the length of string and allocate the required memory space to the array of characters
3. Initialize the string constant by using pointer
Char *pointer_name;
Pointer_name = “string”;
Example:
Char *ptr;
Ptr =”Hello”;
Consider the following program.
#include<stdio.h>
#include<conio.h>
Void main()
{
Char str1[] = {'F','i', 'r', 's', 't','\0'};
Char str2[] = "Second";
Char *ptr;
Int i;
Clrscr();
For (i=0; str1[i]; i++)
Printf("%c", str1[i]);
Printf("\n");
For (i=0; str2[i]; i++)
Printf("%c", str2[i]);
Printf("\n");
Ptr = "Third Sring with pointer";
For (i=0; *ptr; i++)
Printf("%c", *ptr++);
Getch();
}
Output of above program is
First
Second
Third string with pointer
In the above program we used two charater array of name str1 and str2. Str1 array contains the set of characters including null character whereas array str2 contains the string constant. Both the arrays are unsized so compiler automatically calculates the size and assign required amount of memory to arrays. We also deused character pointer ‘ptr’ and assign the value ‘Third string with pointer’ to the pointer ‘ptr’. ‘ptr’ initially pointes to the first letter of the string ie’T’, so inprintf statement we used ‘*ptr++’which is responsible to move the pointer variable to the next element of the string.
As we know pointer is variable which holds the address of another variable whereas pointer to string holds the address of first element of the string. Pointer is the easiest way to manipulate string. With the help of pointer user can manipulate the string on the basis of address of memory location of the string elements.
If we want to modify the third string in the above program ie ‘Third string with pointer’ in such a way that elements storing at the even address will follow ‘$’ sign whereas odd address elements are remain unchanged. For this modification first of all we need to find address location of first element, if it is odd then we need to print ‘$’ sign before second element. As each element in the string require only one byte of memory so the address of next element will be even if address of first element is odd and vice-versa. Consider the following program.
#include<stdio.h>
#include<conio.h>
Void main()
{
Char str1[] = {'F','i', 'r', 's', 't','\0'};
Char str2[] = "Second";
Char *ptr;
Int i,n;
Clrscr();
For (i=0; str1[i]; i++)
Printf("%c", str1[i]);
Printf("\n");
For (i=0; str2[i]; i++)
Printf("%c", str2[i]);
Printf("\n");
Ptr = "Third Sring with pointer";
For (i=0; *ptr; i++)
{
If(i==0)
{
Printf("address of first element ie %c is %d\n",*ptr,ptr);
Printf("\n Modified string is as follows\n");
}
Printf("%c\t", *ptr++);
n=ptr;
If(n%2==0)
Printf("$");
}
Getch();
}
Output of above program is
First
Second
Address of first element ie T is 193
Modified string is as follows
T | $h | I | $r | d | $ | S | $t | r | $i | n | $g |
$w | I | $t | h | $ | p | $o | i | $n | T | $e | r |
Pointer to function is the very important concept in C language. With the help of pointer to function user can access the several different functions on the basis of input data. Function in C language is used to improve reusability of the code. With the help of function user can use the same sample of code for the multiple times. The process of debugging and error correction is also easier with the help of function. Functions divide the complete program into several different modules. Syntax for defining function is as follows
Syntax : Data_type Function_name();
Example: # int fun ( ) ;
In the above syntax ‘fun’ is the function name which is of type integer. The function name ‘fun’ is also work as pointer variable to function. But it is the constant pointer variable so it is illegal to assign value to ‘fun’. Following program illustrate the syntax and use of function
#include<stdio.h>
#include<conio.h>
Void sayhi()
{
Printf("hi everyone");
}
Void main()
{
Clrscr();
Sayhi();
Getch();
}
Output of above program is as follows
Hi everyone
In the above program we create function ‘sayhi’ and use it directly into the main function. Now we will see how to declare pointer to function. Pointer variable name should followed by asterisk sign. Syntax for declaring pointer to function is as follows.
Syntax : Data_type (*pointer_name)();
Example : int (*ptr)();
In the above example we declare pointer variable ‘ptr’ which is responsible to hold the pointer to a function and return an int. Pointer name should be enclosed with the parenthesis as lack of parenthesis pointer variable returns pointer to an int. Following program illustrate the syntax and use of pointer to function
#include<stdio.h>
#include<conio.h>
Void sayhi()
{
Printf("hi everyone");
}
Void main()
{
Void(*sayhiptr)()=sayhi;
Clrscr();
(*sayhiptr)();
Getch();
}
Output of above program is as follows
Hi everyone
In the above program we create function ‘sayhi’ and pointer to function ‘sayhiptr’. The function will not return anything so return type is void. Name of function works as a pointer to function and contains the address of function. So, we assign it to the pointer variable. At last line we call function with the help of pointer.
Function Pointer with Parameter:
Like routine function call, user is also allowed to send pameter with the function pointer.
Consider the following program of passing three integer type parameters to function with the help of function pointer.
#include<stdio.h>
#include<conio.h>
Void total(int m1,int m2, int m3)
{
Int result=m1+m2+m3;
Printf("\n Total marks is %d",result);
}
Void main()
{
Int m1,m2,m3;
Void (*totalptr)()=total;
Clrscr();
Printf("Enter the marks of three subjects");
Scanf("%d %d %d", &m1,&m2,&m3);
(*totalptr)(m1,m2,m3);
Getch();
}
Output of above program is as follows
Enter the marks of three subjects
25
35
30
Total marks is 90
In the above program we create function ‘total’ which accept three integer type values from the main function. Void (*totalptr)()=total; line is responsible to declare and define pointer to function variable. Whereas line(*totalptr)(m1,m2,m3); is used to call function with the help of pointer.
A pointer to structures is where a pointer variable can point to the address of a structure variable. Here is how we can declare a pointer to a structure variable.
1 2 3 4 5 6 7 8 9 10 11 12 | Struct dog { Char name[10]; Char breed[10]; Int age; Char color[10]; };
Struct dog spike;
// declaring a pointer to a structure of type struct dog Struct dog *ptr_dog |
This declares a pointer ptr_dog that can store the address of the variable of type struct dog. We can now assign the address of variable spike to ptr_dog using & operator.
1 | Ptr_dog = &spike; |
Now ptr_dog points to the structure variable spike.
Accessing members using Pointer
There are two ways of accessing members of structure using pointer:
- Using indirection (*) operator and dot (.) operator.
- Using arrow (->) operator or membership operator.
Using indirection (*) operator and dot (.) operator
At this point ptr_dog points to the structure variable spike, so by dereferencing it we will get the contents of the spike. This means spike and *ptr_dog are functionally equivalent. To access a member of structure write *ptr_dog followed by a dot(.) operator, followed by the name of the member.
For example:
(*ptr_dog).name – refers to the name of dog
(*ptr_dog).breed – refers to the breed of dog
Parentheses around *ptr_dog are necessary because the precedence of dot(.) operator is greater than that of indirection (*) operator.
Using arrow (->) operator or membership operator.
To access members using arrow (->) operator write pointer variable followed by -> operator, followed by name of the member.
Ptr_dog->name - refers to the name of dog
Ptr_dog->breed - refers to the breed of dog
We can also modify the value of members using pointer notation.
| Strcpy(ptr_dog->name, "new_name");
In the above expression precedence of arrow operator (->) is greater than that of prefix decrement operator (--), so first -> operator is applied in the expression then its value is decremented by 1. #include<stdio.h>
Struct dog { Char name[10]; Char breed[10]; Int age; Char color[10]; };
Int main() { Struct dog my_dog = {"tyke", "Bulldog", 5, "white"}; Struct dog *ptr_dog; Ptr_dog = &my_dog;
Printf("Dog's name: %s\n", ptr_dog->name); Printf("Dog's breed: %s\n", ptr_dog->breed); Printf("Dog's age: %d\n", ptr_dog->age); Printf("Dog's color: %s\n", ptr_dog->color);
// changing the name of dog from tyke to jack Strcpy(ptr_dog->name, "jack");
// increasing age of dog by 1 year Ptr_dog->age++;
Printf("Dog's new name is: %s\n", ptr_dog->name); Printf("Dog's age is: %d\n", ptr_dog->age);
// signal to operating system program ran fine Return 0; } Expected Output:
1 2 3 4 5 6 7 8 9 Dog's name: tyke Dog's breed: Bulldog Dog's age: 5 Dog's color: white
After changes
Dog's new name is: jack Dog's age is: 6
|