Unit 11
Pointers
- What is pointer variable give example?
Pointers in C language is a variable that stores/points the address of another variable. A Pointer in C is used to allocate memory dynamically i.e. at run time. The pointer variable might be belonging to any of the data type such as int, float, char, double, short etc.
Pointer Syntax : data_type *var_name; Example : int *p; char *p;
Where, * is used to denote that “p” is pointer variable and not a normal variable.
Normal variable stores the value whereas pointer variable stores the address of the variable.
The content of the C pointer always be a whole number i.e. address.
Always C pointer is initialized to null, i.e. int *p = null.
The value of null pointer is 0.
& symbol is used to get the address of the variable.
* symbol is used to get the value of the variable that the pointer is pointing to.
If a pointer in C is assigned to NULL, it means it is pointing to nothing.
Two pointers can be subtracted to know how many elements are available between these two pointers.
But, Pointer addition, multiplication, division are not allowed.
The size of any pointer is 2 byte (for 16 bit compiler).
Example:
#include <stdio.h>
Int main()
{
int *ptr, q;
q = 50;
/* address of q is assigned to ptr */
ptr = &q;
/* display q's value using ptr variable */
printf("%d", *ptr);
return 0;
}
1
2
3
4
5
6
7
8
9
10
11
2. Write a program for addition of two numbers.
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 seventh instruction of above program we used operator ‘%’ and ‘&’ ‘%d’ is the access specifier which tells compiler to take integer value as a input 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 length instruction is as follows. Address of variable C is 1020.
3. What is Pointer Arithmetic?
Pointer arithmetic is slightly different from arithmetic we normally use in our daily life. The only valid arithmetic operations applicable on pointers are:
- Addition of integer to a pointer
- Subtraction of integer to a pointer
- Subtracting two pointers of the same type
The pointer arithmetic is performed relative to the base type of the pointer. For example, if we have an integer pointer ip which contains address 1000, then on incrementing it by 1, we will get 1004 (i.e 1000 + 1 * 4) instead of 1001 because the
Size of the int data type is 4 bytes. If we had been using a system where the size of int is 2 bytes then we would get 1002 ( i.e 1000 + 1 * 2 ).
Similarly, on decrementing it we will get 996 (i.e 1000 - 1 * 4) instead of 999.
So, the expression ip + 4 will point to the address 1016 (i.e 1000 + 4 * 4 ).
Let's take some more examples.
1 2 3 | Int i = 12, *ip = &i; Double d = 2.3, *dp = &d; Char ch = 'a', *cp = &ch;
|
Suppose the address of i, d and ch are 1000, 2000, 3000 respectively, therefore ip, dp and cp are at 1000, 2000, 3000 initially.
4. Explain Passing parameters by reference
A Parameter is the symbolic name for "data" that goes into a function. There are two ways to pass parameters in C: Pass by Value, Pass by Reference.
Pass by Value
Pass by Value, means that a copy of the data is made and stored by way of the name of the parameter. Any changes to the parameter have NO affect on data in the calling function.
Pass by Reference
A reference parameter "refers" to the original data in the calling function. Thus any changes made to the parameter are ALSO MADE TO THE ORIGINAL variable.
There are two ways to make a pass by reference parameter:
ARRAYS
Arrays are always pass by reference in C. Any change made to the parameter containing the array will change the value of the original array.
The ampersand used in the function prototype.
Function ( & parameter_name )
To make a normal parameter into a pass by reference parameter, we use the "& param" notation. The ampersand (&) is the syntax to tell C that any changes made to the parameter also modify the original variable containing the data.
5. Explain pointer to pointer with example
Till this point we are clear about the pointer of different data types in this section we study the pointer of pointer which is also called as double pointer.
Pointer variable is responsible to hold the address of a variable but when user defines pointer to pointer variable then that variable is responsible to hold the address of pointer variable. Pointer to pointer variable is declare by putting extra asterisk sign before the pointer variable. Following is the declaration of pointer to pointer variable
Data-Type**variable-name
Data type is responsible to define type of value stored at the location of pointer variable.
Two asterisk signs indicated that it is pointer to pointer variable.
User can allocate any name to the pointer variable by following all the rules of allocating variable name.
Consider the following program
#include<stdio.h>
#include<conio.h>
Void main()
{
Int n=5;
Int *np,**npp;
Np=&n;
Npp=&np;
Printf("\n value of n is %d",n);
Printf("\n value of n is %d",*np);
Printf("\n value of n is %d",**npp);
Getch();
}
Above program is basic program for double pointer which contains three ‘printf’ statements. The explanation of these statements are as follows.
1.In the first ‘printf’ statement compiler will directly print the value of variable ‘n’ which is ‘5’.
2.In the second ‘printf’ statement compiler will print the value of pointer variable ‘np’. ‘np’ variable contains the address of variable ‘n’ but as we put the asterisk sign before it so it will print the value which is present at the address of variable ‘n’ which is ‘5’
3.In the third printf statement compiler will print the value of pointer to pointer variable ‘npp’. ‘npp’ variable contains the address of pointer variable ‘np’ and ‘np’ variable contains the address of variable n’ but as we put the two asterisk signs before it so it will print the value which is present at the address of variable ‘n’ which is ‘5’. If we put only one asterisk sign the it will print the address of variable ‘n’.
User can allocate any name to the pointer variable by following all the rules of allocating variable
6. Explain Pointers to functions with some of the examples
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_typeFunction_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.
7. What is 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.
8. Explain in detail Dynamic memory allocation
The concept of dynamic memory allocation in c language enables the C programmer to allocate memory at runtime. Dynamic memory allocation in c language is possible by 4 functions of stdlib.h header file.
- Malloc()
- Calloc()
- Realloc()
- Free()
Before learning above functions, let's understand the difference between static memory allocation and dynamic memory allocation.
Static memory allocation | Dynamic memory allocation |
Memory is allocated at compile time. | Memory is allocated at run time. |
Memory can't be increased while executing program. | Memory can be increased while executing program. |
Used in array. | Used in linked list. |
Now let's have a quick look at the methods used for dynamic memory allocation.
Malloc() | Allocates single block of requested memory. |
Calloc() | Allocates multiple block of requested memory. |
Realloc() | Reallocates the memory occupied by malloc() or calloc() functions. |
Free() | Frees the dynamically allocated memory. |
Malloc() function in C
The malloc() function allocates single block of requested memory.
It doesn't initialize memory at execution time, so it has garbage value initially.
It returns NULL if memory is not sufficient.
The syntax of malloc() function is given below:
- Ptr=(cast-type*)malloc(byte-size)
Let's see the example of malloc() function.
- #include<stdio.h>
- #include<stdlib.h>
- Int main(){
- Int n,i,*ptr,sum=0;
- Printf("Enter number of elements: ");
- Scanf("%d",&n);
- Ptr=(int*)malloc(n*sizeof(int)); //memory allocated using malloc
- If(ptr==NULL)
- {
- Printf("Sorry! unable to allocate memory");
- Exit(0);
- }
- Printf("Enter elements of array: ");
- For(i=0;i<n;++i)
- {
- Scanf("%d",ptr+i);
- Sum+=*(ptr+i);
- }
- Printf("Sum=%d",sum);
- Free(ptr);
- Return 0;
- }
Output
Enter elements of array: 3
Enter elements of array: 10
10
10
Sum=30
Calloc() function in C
The calloc() function allocates multiple block of requested memory.
It initially initialize all bytes to zero.
It returns NULL if memory is not sufficient.
The syntax of calloc() function is given below:
- Ptr=(cast-type*)calloc(number, byte-size)
Let's see the example of calloc() function.
- #include<stdio.h>
- #include<stdlib.h>
- Int main(){
- Int n,i,*ptr,sum=0;
- Printf("Enter number of elements: ");
- Scanf("%d",&n);
- Ptr=(int*)calloc(n,sizeof(int)); //memory allocated using calloc
- If(ptr==NULL)
- {
- Printf("Sorry! unable to allocate memory");
- Exit(0);
- }
- Printf("Enter elements of array: ");
- For(i=0;i<n;++i)
- {
- Scanf("%d",ptr+i);
- Sum+=*(ptr+i);
- }
- Printf("Sum=%d",sum);
- Free(ptr);
- Return 0;
- }
Output
Enter elements of array: 3
Enter elements of array: 10
10
10
Sum=30
Realloc() function in C
If memory is not sufficient for malloc() or calloc(), you can reallocate the memory by realloc() function. In short, it changes the memory size.
Let's see the syntax of realloc() function.
- Ptr=realloc(ptr, new-size)
Free() function in C
The memory occupied by malloc() or calloc() functions must be released by calling free() function. Otherwise, it will consume memory until program exit.
Let's see the syntax of free() function.
- Free(ptr)
9. Reading complex pointers explain in brief
There are several things which must be taken into the consideration while reading the complex pointers in C. Lets see the precedence and associativity of the operators which are used regarding pointers.
Operator | Precedence | Associativity |
(), [] | 1 | Left to right |
*, identifier | 2 | Right to left |
Data type | 3 | - |
Here,we must notice that,
- (): This operator is a bracket operator used to declare and define the function.
- []: This operator is an array subscript operator
- * : This operator is a pointer operator.
- Identifier: It is the name of the pointer. The priority will always be assigned to this.
- Data type: Data type is the type of the variable to which the pointer is intended to point. It also includes the modifier like signed int, long, etc).
How to read the pointer: int (*p)[10].
To read the pointer, we must see that () and [] have the equal precedence. Therefore, their associativity must be considered here. The associativity is left to right, so the priority goes to ().
Inside the bracket (), pointer operator * and pointer name (identifier) p have the same precedence. Therefore, their associativity must be considered here which is right to left, so the priority goes to p, and the second priority goes to *.
Assign the 3rd priority to [] since the data type has the last precedence. Therefore the pointer will look like following.
- Char -> 4
- * -> 2
- p -> 1
- [10] -> 3
The pointer will be read as p is a pointer to an array of integers of size 10.
Example
How to read the following pointer?
- Int (*p)(int (*)[2], int (*)void))
Explanation
This pointer will be read as p is a pointer to such function which accepts the first parameter as the pointer to a one-dimensional array of integers of size two and the second parameter as the pointer to a function which parameter is void and return type is the integer.
10. Write Pointer Program to swap two numbers without using the 3rd variable.
- #include<stdio.h>
- Int main(){
- Int a=10,b=20,*p1=&a,*p2=&b;
- Printf("Before swap: *p1=%d *p2=%d",*p1,*p2);
- *p1=*p1+*p2;
- *p2=*p1-*p2;
- *p1=*p1-*p2;
- Printf("\nAfter swap: *p1=%d *p2=%d",*p1,*p2);
- Return 0;
- }
Output
Before swap: *p1=10 *p2=20
After swap: *p1=20 *p2=10