Unit 2
Pointers, Structures, Union & File Handling
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
5.1.1 Introduction
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 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 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;]
A structure can be considered as a template used for defining a collection of variables under a single name. Structures help programmers to group elements of different data types into a single logical unit (Unlike arrays which permit a programmer to group only elements of same data type).
- Why Use Structures
• Ordinary variables can hold one piece of information
• arrays can hold a number of pieces of information of the same data type.
For example, suppose you want to store data about a book. You might want to store its name (a string), its price (a float) and number of pages in it (an int).
If data about say 3 such books is to be stored, then we can follow two approaches:
Construct individual arrays, one for storing names, another for storing prices and still another for storing number of pages.
Use a structure variable.
Suppose we want to create a employee database. Then, we can define a structure
Called employee with three elements id, name and salary. The syntax of this structure is as
Follows:
Struct employee
{ int id;
Char name[50];
Float salary;
};
Note:
Struct keyword is used to declare structure.
Members of structure are enclosed within opening and closing braces.
Usually structure type declaration appears at the top of the source code file, before any variables or functions are defined or maintained in separate header file.
Declaration of Structure reserves no space.
It is nothing but the “ Template / Map / Shape ” of the structure .
Memory is created , very first time when the variable is created / Instance is created.
- Structure variable declaration:
We can declare the variable of structure in two ways
- Declare the structure inside main function
- Declare the structure outside the main function.
1. Declare the structure inside main function
Following example show you, how structure variable is declared inside main function
Struct employee
{
Int id;
Char name[50];
Float salary;
};
Int main()
{
Struct employee e1, e2;
Return 0;
}
In this example the variable of structure employee is created inside main function that e1 ,e2.
2. Declare the structure outside main function
Following example show you, how structure variable is declared outside the main function
Struct employee
{
Int id;
Char name[50];
Float salary;
}e1,e2;
- Memory allocation for structure
Memory is allocated to the structure only when we create the variable of structure.
Consider following example
- Structure Initialization
1. When we declare a structure, memory is not allocated for un-initialized variable.
2. Let us discuss very familiar example of structure student , we can initialize structure variable
In different ways –
Way 1 : Declare and Initialize
Struct student
{
Char name[20];
Int roll;
Float marks;
}std1 = { "Poonam",89,78.3 };
In the above code snippet, we have seen that structure is declared and as soon as after declaration we
Have initialized the structure variable.
Std1 = { "Poonam",89,78.3 }
This is the code for initializing structure variable in C programming
Way 2 : Declaring and Initializing Multiple Variables
Struct student
{
Char name[20];
Int roll;
Float marks;
}
Std1 = {"Poonam" ,67, 78.3};
Std2 = {"Vishal",62, 71.3};
In this example, we have declared two structure variables in above code. After declaration of variable we have initialized two variable.
Std1 = {"Poonam" ,67, 78.3};
Std2 = {"Vishal",62, 71.3};
Way 3 : Initializing Single member
Struct student
{
Int mark1;
Int mark2;
Int mark3;
} sub1={67};
Though there are three members of structure,only one is initialized , Then remaining two members
Are initialized with Zero. If there are variables of other data type then their initial values will be –
Data Type Default value if not initialized
Integer 0
Float 0.00
Char NULL
Way 4 : Initializing inside main
Struct student
{
Int mark1;
Int mark2;
Int mark3;
};
Void main()
{
Struct student s1 = {89,54,65};
- - - - --
- - - - --
- - - - --
};
When we declare a structure then memory won’t be allocated for the structure. i.e only writing below
Declaration statement will never allocate memory
Struct student
{
Int mark1;
Int mark2;
Int mark3;
};
We need to initialize structure variable to allocate some memory to the structure.
Struct student s1 = {89,54,65};
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
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 |
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.
Unions are quite similar to the structures in C. Union is also a derived type as
Structure. Union can be defined in same manner as structures just the keyword
Used in defining union in union where keyword used in defining structure was struct.
Union car
{
Char name[50];
Int price;
};
Union variables can be created in similar manner as structure variable.
Union car
{
Char name[50];
Int price;
}c1, c2, *c3;
OR;
Union car
{
Char name[50];
Int price;
};
-------Inside Function-----------
Union car c1, c2, *c3;
In both cases, union variables c1, c2 and union pointer variable c3 of type union
Car is created.
- Memory allocation for union
Like structure memory is allocated to union only when we create the variable of it.
The memory is allocated to union according to the largest data members of the union.
- Accessing members of an union
Array elements are accessed using the Subscript variable , Similarly Union members are accessed using dot [.] operator.
(.) is called as “union member Operator”.
Use this Operator in between “Union variable” & “member name”
Union employee
{
Int id;
Char name[50];
Float salary;
} ;
Void main()
{
Union employee e1= { 1, “ABC”, 50000 };
Printf(“%d”, e. Id);
Printf(“%s”, e. Name);
}
O/P- garbage value, ABC