Unit 4
Unit 4
Pointers
Definition: The pointer in C language is a variable which stores the address of another variable.
Pointers are used to access memory and manipulate the address. This variable can be of type int, char,
array, function, or any other pointer.
Initialize a pointer:
After declaring a pointer, we initialize it like standard variables with a variable address. To get the
address of a variable, we use the ampersand (&)operator, placed before the name of a variable whose
address we need.
Syntax: pointer = &variable;
Eg: double a = 10;
Page 2 of 57
Programming for Problem Solving Using ‘C’ Unit-IV
double *p;
p = &a;
Concept of Pointers:
int a=10;
a
10
1004
Whenever a variable is declared in a program, system allocates a location i.e an address to that
variable in the memory, to hold the assigned value.(Fig.1)
This location has its own address number
Let us assume that system has allocated memory location 80F for a variable a. (above
mentioned)
Pointer Variables:
The memory addresses are also just numbers, they can also be assigned to some other variable.
The variables which are used to hold memory addresses are called Pointer variables.
A pointer variable is therefore nothing but a variable which holds an address of some other
variable.
Page 3 of 57
Programming for Problem Solving Using ‘C’ Unit-IV
Address in C
If you have a variable var in your program, &var will give you its address in the memory.
We have used address numerous times while using the scanf() function.
scanf("%d", &var);
Here, the value entered by the user is stored in the address of var variable. Let's take a working
example.
#include <stdio.h>
int main()
{
int var = 5;
printf("var: %d\n", var);
// Notice the use of & before var
printf("address of var: %p", &var);
return 0;
}
Output
var: 5
address of var: 2686778
Note: You will probably get a different address when you run the above code.
C Pointers
Pointers (pointer variables) are special variables that are used to store addresses rather than values.
Pointer Syntax
Here is how we can declare pointers.
Page 4 of 57
Programming for Problem Solving Using ‘C’ Unit-IV
int* p;
int *p1;
int * p2;
// Output: 5
Here, the address of c is assigned to the pc pointer. To get the value stored in that address, we
used *pc.
Note: In the above example, pc is a pointer, not *pc. You cannot and should not do something
like *pc = &c;
Page 5 of 57
Programming for Problem Solving Using ‘C’ Unit-IV
By the way, * is called the dereference operator (when working with pointers). It operates on a pointer
and gives the value stored in that pointer.
Then, the address of d is assigned to the pc pointer using pc = &d;. Since d is -15, *pc gives us -15.
Address of c: 2686784
Page 7 of 57
Programming for Problem Solving Using ‘C’ Unit-IV
Value of c: 2
c = 22;
This assigns 22 to the variable c. That is, 22 is stored in the memory location of variable c.
pc = &c;
c = 11;
Page 8 of 57
Programming for Problem Solving Using ‘C’ Unit-IV
*pc = 2;
This change the value at the memory location pointed by the pointer pc to 2.
POINTERS TO POINTERS:
A variable that is a pointer to a pointer must be declared as such. This is done by placing an additional
asterisk in front of its name.
Syntax: datatype **pointerName ; Eg:int **var;
Example Program:
#include <stdio.h>
void main ()
{
int var;
int *ptr;
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);
getch();
Page 9 of 57
Programming for Problem Solving Using ‘C’ Unit-IV
}
Output:
Value of var = 3000
Value available at *ptr = 3000
Value available at **pptr = 3000
COMPATIBILITY:
Two pointer types with the same type qualifiers are compatible if they point to objects of compatible
types. The composite type for two compatible pointer types is the similarly qualified pointer to the
composite type.
The following example shows compatible declarations for the assignment operation:
float subtotal;
float * sub_ptr;
sub_ptr = &subtotal;
printf("The subtotal is %f\n", *sub_ptr);
The next example shows incompatible declarations for the assignment operation:
double league;
int * minor;
minor = &league; /* error */
Pointers have a type associated with them, such as char, int, float, etc. Each pointer takes on the
attributes of the type to which it refers to in addition to its own attributes.
Compatibility types are:
a) Pointer Size Compatibility
b) Dereference Type Compatibility
c) Casting Pointers
d) Dereference Level Compatibility
Page 10 of 57
Programming for Problem Solving Using ‘C’ Unit-IV
Example: Prints the size of each pointer and the size of each referenced variable
#include <stdio.h>
void main()
{
int a = 10;
int *pa = &a;
char b = 'x';
char *pb = &b;
float c = 10.01;
float *pc = &c;
printf("Pointer Example Program : Print Size of Different types Using sizeof\n");
printf("\n sizeof(a): = %d", sizeof(a));
printf("\n sizeof(*pa): = %d", sizeof(*pa));
printf("\n sizeof(b): = %d", sizeof(b));
printf("\n sizeof(*pb): = %d", sizeof(*pb));
printf("\n sizeof(c): = %d", sizeof(c));
printf("\n sizeof(*pc): = %d", sizeof(*pc));
getch();
}
Output:
Pointer Example Program : Print Size of Different types Using sizeof
sizeof(a) : = 4
sizeof(*pa) : = 4
sizeof(b) : = 1
sizeof(*pb) : = 1
sizeof(c) : = 4
sizeof(*pc) : = 4
Page 11 of 57
Programming for Problem Solving Using ‘C’ Unit-IV
The exception to the reference type compatibility rule is the pointer to Void.
c) Casting Pointers:
The problem of type incompatibility can be solved by using casting.
An explicit assignment between incompatible pointer types is done by using a cast operator.
For example,
pc=(char *)&a; /*pc is a character pointer and a is a integer pointer */
This converts an integer pointer to a char and assigns the value to pc.
d) Dereference Level Compatibility:
A pointer to int is not compatible with a pointer-to-pointer to int.
The pointer to int has a reference type of int, while a pointer-to-pointer to int has a reference type of
pointer to int
1. Static memory: This is where variables, which are defined outside of functions, are located. it
specifies their scope to be local to the current module. Variables that are defined inside of a function,
which are explicitly declared static, are also stored in static memory.
2. Dynamic Memory: 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.
1. malloc()
2. calloc()
3. realloc()
4. free()
Page 13 of 57
Programming for Problem Solving Using ‘C’ Unit-IV
1. malloc():
malloc () function is used to allocate space in memory during the execution of the program.
malloc () does not initialize the memory allocated during execution. It carries garbage value.
malloc () function returns null pointer if it couldn’t able to allocate requested amount of
memory.
Syntax: ptr=(cast-type*)malloc(byte-size);
2. calloc():
The calloc() function allocates multiple block of requested memory.
It initially initialize all bytes to zero.
It returns NULL if memory is not sufficient.
3. realloc():
If memory is not sufficient for malloc() or calloc(), you can reallocate the memory by realloc()
function. In short, it changes the memory size.
4. free():
The memory occupied by malloc() or calloc() functions must be released by calling free() function.
Otherwise, it will consume memory until program exit.
Syntax: free(ptr);
Example:
C Program to Store Information Using Structures with Dynamic Memory Allocation
#include <stdio.h>
#include<stdlib.h>
struct course
{
int marks;
char subject[30];
};
void main()
{
struct course *ptr;
int i, noofRecords;
printf("Enter number of records: ");
scanf("%d", &noofRecords);
// Allocates the memory for noofRecords structures with pointer ptr pointing to the base
address.
ptr = (struct course*) malloc (noOfRecords * sizeof(struct course));
for(i = 0; i < noofRecords; ++i)
{
printf("Enter name of the subject and marks respectively:\n");
scanf("%s %d", &(ptr+i)->subject, &(ptr+i)->marks);
}
printf("Displaying Information:\n"); for(i = 0; i < noofRecords ; ++i)
{
printf("%s\t%d\n", (ptr+i)->subject, (ptr+i)->marks);
}
Page 15 of 57
Programming for Problem Solving Using ‘C’ Unit-IV
getch();
}
Output:
Memory size can’t be modified while Memory size can be modified while
execution. execution.
Example: array Example: Linked list
malloc() calloc()
malloc () doesn’t initializes the allocated calloc () initializes the allocated memory to
memory. It contains garbage values zero
Page 16 of 57
Programming for Problem Solving Using ‘C’ Unit-IV
type cast must be done since this function Same as malloc () function int *ptr;
returns void pointer ptr = (int*)calloc(20,sizeof(int));
int *ptr;
ptr = (int*)malloc(sizeof(int)*20 );
Here variable arr will give the base address, which is a constant pointer pointing to the first element of
the array, arr[0]. Hence arr contains the address of arr[0] i.e 1000.
Hence arr has two purposes
1. It is the name of the array
2. It acts as a pointer pointing towards the first element in the array.
Pointer to Array: We can use a pointer to point to an array, and then we can use that pointer to access
the array elements.
#include <stdio.h>
void main()
{
Page 17 of 57
Programming for Problem Solving Using ‘C’ Unit-IV
int i;
int a[5] = {1, 2, 3, 4, 5};
int *p = &a[0]; // same as int*p = a;
for (i = 0; i < 5; i++)
{
printf("%d", *p);
p++;
}
getch();
}
Output:
In the above program, the pointer *p will print all the values stored in the array one by one.
POINTER ARITHMETIC:
A pointer in c is an address, which is a numeric value. Therefore, you can perform arithmetic
operations on a pointer just as you can on a numeric value.
Following arithmetic operations are possible on the pointer in C language:
1. Pointer increment:
Increment operator when used with a pointer variable returns next address pointed by the pointer. The
next address returned is the sum of current pointed address and size of pointer data type.
Example:
#include <stdio.h>
void main()
{
int i;
int a[5] = {1, 2, 3, 4, 5};
int *p = &a[0]; // same as int*p = a;
for (i = 0; i < 5; i++)
{
printf("Address of a[%d] = %x\n", i, p );
printf("Value of a[%d] = %d\n", i, *p );
p++;
Page 18 of 57
Programming for Problem Solving Using ‘C’ Unit-IV
}
getch();
}
Output:
2. Pointer decrement:
Decrement operator returns the previous address pointed by the pointer. The returned address is the
difference of current pointed address and size of pointer data type.
#include <stdio.h>
void main()
{
int i;
int a[5] = {1, 2, 3, 4, 5};
int *p = &a[4]; // same as int*p = a;
for (i = 5; i > 0; i--)
{
printf("Address of a[%d] = %x\n", i, p );
printf("Value of a[%d] = %d\n", i, *p );
p--;
}
getch();
}
Output:
3. Pointer Addition:
We can add a value to the pointer variable. Adding any number to a pointer will give an address.
Syntax: new_address= current_address + (number * size_of(data type));
Example:
Page 19 of 57
Programming for Problem Solving Using ‘C’ Unit-IV
p=p+3;
printf("After adding 3: Address of p variable is %u \n",p);
return 0;
}
Output:
Address of p variable is 3214864300
After adding 3: Address of p variable is 3214864312
As you can see, the address of p is 3214864300. But after adding 3 with p variable, it is 3214864312,
i.e., 4*3=12 increment,since integer value occupies 4-byte memory in 64-bit Operating system.
4. Pointer Subtraction:
Like pointer addition, we can subtract a value from the pointer variable.Subtracting any number from
a pointer will give an address.
Syntax: new_address= current_address - (number * size_of(data type));
Example:
#include<stdio.h>
int main()
{
int number=50;
int *p; //pointer to int
p=&number; //stores the address of number variable
printf("Address of p variable is %u \n",p);
p=p-3; //subtracting 3 from pointer variable
printf("After subtracting 3: Address of p variable is %u \n",p);
return 0;
Page 20 of 57
Programming for Problem Solving Using ‘C’ Unit-IV
}
Output:
Address of p variable is 3214864300
After subtracting 3: Address of p variable is 3214864288
You can see after subtracting 3 from the pointer variable, it is 12 (4*3) less than the previous address
value.
5. Pointer comparison:
In C, you can compare two pointers using relational operator. You can perform six different type of
pointer comparison <, >, <=, >=, == and !=.Pointer comparison compares two pointer addresses to
which they point to, instead of comparing their values. Pointer comparisons are useful,If you want to
check if two pointer points to same location.
Example:
int main()
{
int num = 10;
int *ptr1 = # // ptr1 points to num
int *ptr2 = # // ptr2 also points to num
printf(“address of ptr1 is %u”,ptr1);
printf(“address of ptr2 is %u”,ptr2);
if(ptr1 == ptr2)
{
ptr2++;
printf(“modified address of ptr2 is %u”,ptr2);
}
return 0;
}
Output:
Page 21 of 57
Programming for Problem Solving Using ‘C’ Unit-IV
ARRAY OF POINTERS:
Just like we can declare an array of int, float or char etc, we can also declare an array of pointers. Array
of pointers is an indexed set of variables, where the variables are pointers. An array of pointers is
useful in the same way as all arrays, that is it allows you to index a large set of variables.
Syntax: datatype *array_name[size]; Eg: int *arr[5];
Page 22 of 57
Programming for Problem Solving Using ‘C’ Unit-IV
PROGRAMMING APPLICATION:
Dynamic Array:
This program creates a dynamic array where the programmer can choose the number of rows and
number of elements that can be stored per a row (coloumns) dynamically at run time.
#include <stdio.h>
#include <stdlib.h>
void main()
{
int r, c;
printf("enter number of rows you want to create \n");
scanf("%d",&r);
printf("number of elements you want to insert per row \n");
scanf("%d",&c);
int *arr = (int *)malloc(r * c * sizeof(int));
int i, j, count = 0;
for (i = 0; i < r; i++)
{
(j = 0; j < c; j++)
{
printf("%d ", *(arr + i*c + j));
}
for (j = 0; j < c; j++)
{
*(arr + i*c + j) = ++count;
}
}
for (i = 0; i < r; i++)
{
for (j = 0; j < c; j++)
getch();
}
Output:
Page 24 of 57
Programming for Problem Solving Using ‘C’ Unit-IV
Ex:
#include <stdio.h>
int* findLarger(int*, int*);
void main()
{
int numa=0; int numb=0; int *result;
printf("\n\n Pointer : Show a function returning pointer :\n");
printf(" \n");
printf(" Input the first number : ");
scanf("%d", &numa);
printf(" Input the second number : ");
scanf("%d", &numb);
result=findLarger(&numa, &numb);
printf(" The number %d is larger. \n\n",*result);
}
int* findLarger(int *n1, int *n2)
{
if(*n1 > *n2) return n1; else
return n2;
}
Output:
Pointer : Show a function returning pointer :
Page 25 of 57
Programming for Problem Solving Using ‘C’ Unit-IV
Call by Reference:
In call by reference parameter passing method, the address of the actual parameters is passed to the
called function and is received by the formal parameters (pointers). Whenever we use these formal
parameters in called function, they directly access the memory locations of actual parameters. So the
changes made on the formal parameters effects the values of actual parameters.
Eg:
#include<stdio.h>
#include<conio.h>
void main()
{
int num1, num2 ;
void swap(int *,int *) ; // function declaration clrscr() ;
num1 = 10 ;
num2 = 20 ;
printf("\nBefore swap: num1 = %d, num2 = %d", num1, num2) ;
swap(&num1, &num2) ; // calling function
printf("\nAfter swap: num1 = %d, num2 = %d", num1, num2);
getch() ;
}
void swap(int *a, int *b) // called function
{
int temp ; temp = *a ;
*a = *b ;
*b = temp ;
}
Output:
Page 26 of 57
Programming for Problem Solving Using ‘C’ Unit-IV
Structures in C:
In C programming language, a structure is a collection of elements of the different data type. The
structure is used to create user-defined data type in the C programming language. As the structure used
to create a user-defined data type, the structure is also said to be “user-defined data type in C”.
In other words, a structure is a collection of non-homogeneous elements. Using structure we can define
new data types called user-defined data types that holds multiple values of the different data type. The
formal definition of structure is as follows...
Structure is a collection of different type of elements under a single name that acts as
user defined data type in C.
Generally, structures are used to define a record in the c programming language. Structures allow us to
combine elements of a different data type into a group. The elements that are defined in a structure are
called members of structure.
How to create structure?
To create structure in c, we use the keyword called "struct". We use the following syntax to create
structures in c programming language.
struct <structure_name>
{
data_type member1;
data_type member2, member3;
.
.
};
Following is the example of creating a structure called Student which is used to hold student record.
Creating structure in C
struct Student
{
char stud_name[30];
int roll_number;
float percentage;
};
Importent Points to be Remembered:
Every structure must terminated with semicolon symbol (;).
"struct" is a keyword, it must be used in lowercase letters only.
Page 27 of 57
Programming for Problem Solving Using ‘C’ Unit-IV
long as the variable of a structure is created no memory is allocated. The size of memory allocated is
equal to the sum of memory required by individual members of that structure. In the above example
program, the variables stud_1 and stud_2 are allocated with 36 bytes of memory each.
When the above code is compiled and executed, it produces the following result −
Book 1 title : C Programming
Book 1 author : Nuha Ali
Book 1 subject : C Programming Tutorial
Book 1 book_id : 6495407
Book 2 title : Telecom Billing
Book 2 author : Zara Ali
Book 2 subject : Telecom Billing Tutorial
Book 2 book_id : 6495700
Page 30 of 57
Programming for Problem Solving Using ‘C’ Unit-IV
Nested structures:
C provides us the feature of nesting one structure within another structure by using which, complex
data types are created. For example, we may need to store the address of an entity employee in a
structure. The attribute address may also have the subparts as street number, city, state, and pin code.
Hence, to store the address of the employee, we need to store the address of the employee into a
separate structure and nest the structure address into the structure employee.
Consider the following program.
#include<stdio.h>
struct address
{
char city[20];
int pin;
char phone[14];
};
struct employee
{
char name[20];
struct address add;
};
void main ()
{
struct employee emp;
printf("Enter employee information?\n");
scanf("%s %s %d %s",emp.name,emp.add.city, &emp.add.pin, emp.add.phone);
printf("Printing the employee information. .. \n");
printf("name: %s\nCity: %s\nPincode: %d\nPhone: %s",emp.name,emp.add.city,emp.add.pin,emp.a
dd.phone);
}
Output
Enter employee information?
Arun
Delhi
110001
Page 31 of 57
Programming for Problem Solving Using ‘C’ Unit-IV
1234567890
Printing the employee information....
name: Arun
City: Delhi
Pincode: 110001
Phone: 1234567890
The structure can be nested in the following ways.
1. By separate structure
2. By Embedded structure
1) Separate structure
Here, we create two structures, but the dependent structure should be used inside the main structure as
a member.
Consider the following example.
struct Date
{
int dd;
int mm;
int yyyy;
};
struct Employee
{
int id;
char name[20];
struct Date doj;
}emp1;
As you can see, doj (date of joining) is the variable of type Date. Here doj is used as a member in
Employee structure. In this way, we can use Date structure in many structures.
2) Embedded structure
The embedded structure enables us to declare the structure inside the structure. Hence, it requires less
line of codes but it cannot be used in multiple data structures. Consider the following example.
struct Employee
Page 32 of 57
Programming for Problem Solving Using ‘C’ Unit-IV
{
int id;
char name[20];
struct Date
{
int dd;
int mm;
int yyyy;
}doj;
}emp1;
}e1;
int main( )
{
//storing employee information
e1.id=101;
strcpy(e1.name, "Sonoo Jaiswal");//copying string into char array
e1.doj.dd=10;
e1.doj.mm=11;
e1.doj.yyyy=2014;
//printing first employee information
printf( "employee id : %d\n", e1.id);
printf( "employee name : %s\n", e1.name);
printf( "employee date of joining (dd/mm/yyyy) : %d/%d/%d\n", e1.doj.dd,e1.doj.mm,e1.doj.yyyy);
return 0;
}
Output:
employee id : 101
employee name : Sonoo Jaiswal
employee date of joining (dd/mm/yyyy) : 10/11/2014
C Array of Structures
Why use an array of structures?
Consider a case, where we need to store the data of 5 students. We can store it by using the structure as
given below.
#include<stdio.h>
struct student
{
char name[20];
int id;
float marks;
};
Page 34 of 57
Programming for Problem Solving Using ‘C’ Unit-IV
void main()
{
struct student s1,s2,s3;
int dummy;
printf("Enter the name, id, and marks of student 1 ");
scanf("%s %d %f",s1.name,&s1.id,&s1.marks);
scanf("%c",&dummy);
printf("Enter the name, id, and marks of student 2 ");
scanf("%s %d %f",s2.name,&s2.id,&s2.marks);
scanf("%c",&dummy);
printf("Enter the name, id, and marks of student 3 ");
scanf("%s %d %f",s3.name,&s3.id,&s3.marks);
scanf("%c",&dummy);
printf("Printing the details. .. \n");
printf("%s %d %f\n",s1.name,s1.id,s1.marks);
printf("%s %d %f\n",s2.name,s2.id,s2.marks);
printf("%s %d %f\n",s3.name,s3.id,s3.marks);
}
Output
Enter the name, id, and marks of student 1 James 90 90
Enter the name, id, and marks of student 2 Adoms 90 90
Enter the name, id, and marks of student 3 Nick 90 90
Printing the details....
James 90 90.000000
Adoms 90 90.000000
Nick 90 90.000000
In the above program, we have stored data of 3 students in the structure. However, the complexity of
the program will be increased if there are 20 students. In that case, we will have to declare 20 different
structure variables and store them one by one. This will always be tough since we will have to declare
a variable every time we add a student. Remembering the name of all the variables is also a very tricky
task. However, c enables us to declare an array of structures by using which, we can avoid declaring
the different structure variables; instead we can make a collection containing all the structures that
store the information of different entities.
Page 35 of 57
Programming for Problem Solving Using ‘C’ Unit-IV
Array of Structures in C
An array of structres in C can be defined as the collection of multiple structures variables where each
variable contains information about different entities. The array of structures in C are used to store
information about multiple entities of different data types. The array of structures is also known as the
collection of structures.
Let's see an example of an array of structures that stores information of 5 students and prints it.
#include<stdio.h>
#include <string.h>
struct student
{
int rollno;
char name[10];
};
int main()
{
int i;
struct student st[5];
printf("Enter Records of 5 students");
for(i=0;i<5;i++)
{
printf("\nEnter Rollno:");
scanf("%d",&st[i].rollno);
printf("\nEnter Name:");
scanf("%s",&st[i].name);
Page 36 of 57
Programming for Problem Solving Using ‘C’ Unit-IV
}
printf("\nStudent Information List:");
for(i=0;i<5;i++)
{
printf("\nRollno:%d, Name:%s",st[i].rollno,st[i].name);
}
return 0;
}
Output:
Enter Records of 5 students
Enter Rollno:1
Enter Name:Sonoo
Enter Rollno:2
Enter Name:Ratan
Enter Rollno:3
Enter Name:Vimal
Enter Rollno:4
Enter Name:James
Enter Rollno:5
Enter Name:Sarfraz
Page 37 of 57
Programming for Problem Solving Using ‘C’ Unit-IV
In other words, structures pointing to the same type of structures are self-referential in nature.
Example:
struct node
{
int data1;
char data2;
struct node* link;
};
int main()
{
struct node ob;
return 0;
}
In the above example ‘link’ is a pointer to a structure of type ‘node’. Hence, the structure ‘node’ is a
self-referential structure with ‘link’ as the referencing pointer.
An important point to consider is that the pointer should be initialized properly before accessing, as by
default it contains garbage value.
1. Self Referential Structure with Single Link: These structures can have only one self-pointer
as their member. The following example will show us how to connect the objects of a self-
referential structure with the single link and access the corresponding data members. The
connection formed is shown in the following figure.
Page 38 of 57
Programming for Problem Solving Using ‘C’ Unit-IV
#include <stdio.h>
struct node
{
int data1;
char data2;
struct node* link;
};
int main()
{
struct node ob1; // Node1
// Initialization
ob1.link = NULL;
ob1.data1 = 10;
ob1.data2 = 20;
struct node ob2; // Node2
// Initialization
ob2.link = NULL;
ob2.data1 = 30;
ob2.data2 = 40;
// Linking ob1 and ob2
ob1.link = &ob2;
// Accessing data members of ob2 using ob1
printf("%d", ob1.link->data1);
printf("\n%d", ob1.link->data2);
return 0;
}
Output:
30
40
Page 39 of 57
Programming for Problem Solving Using ‘C’ Unit-IV
2. Self Referential Structure with Multiple Links: Self referential structures with multiple links can
have more than one self-pointers. Many complicated data structures can be easily constructed using
these structures. Such structures can easily connect to more than one nodes at a time. The following
example shows one such structure with more than one links.
The connections made in the above example can be understood using the following figure.
#include <stdio.h>
struct node
{
int data;
struct node* prev_link;
struct node* next_link;
};
int main()
{
struct node ob1; // Node1
// Initialization
ob1.prev_link = NULL;
ob1.next_link = NULL;
ob1.data = 10;
struct node ob2; // Node2
// Initialization
ob2.prev_link = NULL;
ob2.next_link = NULL;
ob2.data = 20;
Page 40 of 57
Programming for Problem Solving Using ‘C’ Unit-IV
Output:
10 20 30
10 20 30
10 20 30
In the above example we can see that ‘ob1’, ‘ob2’ and ‘ob3’ are three objects of the self referential
structure ‘node’. And they are connected using their links in such a way that any of them can easily
Page 41 of 57
Programming for Problem Solving Using ‘C’ Unit-IV
access each other’s data. This is the beauty of the self referential structures. The connections can be
manipulated according to the requirements of the programmer.
Applications:
Self referential structures are very useful in creation of other complex data structures like:
1. Linked Lists 2. Stacks 3. Queues
4. Trees 5. Graphs etc
Page 42 of 57
Programming for Problem Solving Using ‘C’ Unit-IV
Page 43 of 57
Programming for Problem Solving Using ‘C’ Unit-IV
for(int i=jan;i<=december;i++)
{
printf("%d, ",i);
}
return 0;
}
In the above code, we have created a type of enum named as months which consists of all the names of
months. We have assigned a '1' value, and all the other months will be given a value as the previous
one plus one. Inside the main() method, we have defined a for loop in which we initialize the 'i'
variable by jan, and this loop will iterate till December.
Output
Page 44 of 57
Programming for Problem Solving Using ‘C’ Unit-IV
break;
case monday:
printf("Today is monday");
break;
case tuesday:
printf("Today is tuesday");
break;
case wednesday:
printf("Today is wednesday");
break;
case thursday:
printf("Today is thursday");
break;
case friday:
printf("Today is friday");
break;
case saturday:
printf("Today is saturday");
break;
}
return 0;
}
Output
Page 45 of 57
Programming for Problem Solving Using ‘C’ Unit-IV
If we do not provide any value to the enum names, then the compiler will automatically assign
the default values to the enum names starting from 0.
We can also provide the values to the enum name in any order, and the unassigned names will
get the default value as the previous one plus one.
The values assigned to the enum names must be integral constant, i.e., it should not be of other
types such string, float, etc.
All the enum names must be unique in their scope, i.e., if we define two enum having same
scope, then these two enums should have different enum names otherwise compiler will throw
an error.
Let's understand this scenario through an example.
#include <stdio.h>
enum status{success, fail};
enum boolen{fail,pass};
int main(void)
{
printf("The value of success is %d", success);
return 0;
}
Output
In enumeration, we can define an enumerated data type without the name also.
#include <stdio.h>
enum {success, fail} status;
Page 46 of 57
Programming for Problem Solving Using ‘C’ Unit-IV
int main(void)
{
status=success;
printf("The value of status is %d", status);
return 0;
}
Output
The above two statements can be written in a single statement by using the enum type.
enum status{pass, success};
The enum type follows the scope rules while macro does not follow the scope rules.
In Enum, if we do not assign the values to the enum names, then the compiler will
automatically assign the default value to the enum names. But, in the case of macro, the values
need to be explicitly assigned.
The type of enum in C is an integer, but the type of macro can be of any type.
typedef in C
The typedef is a keyword used in C programming to provide some meaningful names to the already
existing variable in the C program. It behaves similarly as we define the alias for the commands. In
short, we can say that this keyword is used to redefine the name of an already existing variable.
Syntax of typedef
typedef <existing_name> <alias_name>
In the above syntax, 'existing_name' is the name of an already existing variable while 'alias name' is
another name given to the existing variable.
For example, suppose we want to create a variable of type unsigned int, then it becomes a tedious task
if we want to declare multiple variables of this type. To overcome the problem, we use a
typedef keyword.
Page 47 of 57
Programming for Problem Solving Using ‘C’ Unit-IV
In the above structure declaration, we have created the variable of student type by writing the
following statement:
struct student s1;
The above statement shows the creation of a variable, i.e., s1, but the statement is quite big. To avoid
such a big statement, we use the typedef keyword to create the variable of type student.
struct student
{
char name[20];
int age;
};
typedef struct student stud;
stud s1, s2;
In the above statement, we have declared the variable stud of type struct student. Now, we can use
the stud variable in a program to create the variables of type struct student.
From the above declarations, we conclude that typedef keyword reduces the length of the code and
complexity of data types. It also helps in understanding the program.
{
stud s1;
printf("Enter the details of student s1: ");
printf("\nEnter the name of the student:");
scanf("%s",&s1.name);
printf("\nEnter the age of student:");
scanf("%d",&s1.age);
printf("\n Name of the student is : %s", s1.name);
printf("\n Age of the student is : %d", s1.age);
return 0;
}
Output
Page 50 of 57
Programming for Problem Solving Using ‘C’ Unit-IV
#include <stdio.h>
#include <string.h>
struct Books
{
char title[50];
char author[50];
char subject[100];
int book_id;
};
/* function declaration */
void printBook( struct Books book );
int main( )
{
struct Books Book1; /* Declare Book1 of type Book */
struct Books Book2; /* Declare Book2 of type Book */
/* book 1 specification */
strcpy( Book1.title, "C Programming");
strcpy( Book1.author, "Nuha Ali");
strcpy( Book1.subject, "C Programming Tutorial");
Book1.book_id = 6495407;
/* book 2 specification */
strcpy( Book2.title, "Telecom Billing");
strcpy( Book2.author, "Zara Ali");
strcpy( Book2.subject, "Telecom Billing Tutorial");
Book2.book_id = 6495700;
/* print Book1 info */
printBook( Book1 );
/* Print Book2 info */
printBook( Book2 );
return 0;
}
void printBook( struct Books book )
Page 51 of 57
Programming for Problem Solving Using ‘C’ Unit-IV
{
printf( "Book title : %s\n", book.title);
printf( "Book author : %s\n", book.author);
printf( "Book subject : %s\n", book.subject);
printf( "Book book_id : %d\n", book.book_id);
}
When the above code is compiled and executed, it produces the following result −
Book title : C Programming
Book author : Nuha Ali
Book subject : C Programming Tutorial
Book book_id : 6495407
Book title : Telecom Billing
Book author : Zara Ali
Book subject : Telecom Billing Tutorial
Book book_id : 6495700
Page 52 of 57
Programming for Problem Solving Using ‘C’ Unit-IV
int book_id;
};
/* function declaration */
void printBook( struct Books *book );
int main( )
{
struct Books Book1; /* Declare Book1 of type Book */
struct Books Book2; /* Declare Book2 of type Book */
/* book 1 specification */
strcpy( Book1.title, "C Programming");
strcpy( Book1.author, "Nuha Ali");
strcpy( Book1.subject, "C Programming Tutorial");
Book1.book_id = 6495407;
/* book 2 specification */
strcpy( Book2.title, "Telecom Billing");
strcpy( Book2.author, "Zara Ali");
strcpy( Book2.subject, "Telecom Billing Tutorial");
Book2.book_id = 6495700;
/* print Book1 info by passing address of Book1 */
printBook( &Book1 );
/* print Book2 info by passing address of Book2 */
printBook( &Book2 );
return 0;
}
void printBook( struct Books *book )
{
printf( "Book title : %s\n", book->title);
printf( "Book author : %s\n", book->author);
printf( "Book subject : %s\n", book->subject);
printf( "Book book_id : %d\n", book->book_id);
}
When the above code is compiled and executed, it produces the following result −
Book title : C Programming
Page 53 of 57
Programming for Problem Solving Using ‘C’ Unit-IV
Union:
A union is a special data type available in C that allows to store different data types in the same
memory location. You can define a union with many members, but only one member can contain a
value at any given time. Unions provide an efficient way of using the same memory location for
multiple-purpose.
Defining a Union
To define a union, you must use the union statement in the same way as you did while defining a
structure. The union statement defines a new data type with more than one member for your program.
The format of the union statement is as follows −
union [union tag]
{
member definition;
member definition;
...
member definition;
} [one or more union variables];
The union tag is optional and each member definition is a normal variable definition, such as int i; or
float f; or any other valid variable definition. At the end of the union's definition, before the final
semicolon, you can specify one or more union variables but it is optional. Here is the way you would
define a union type named Data having three members i, f, and str −
union Data
{
int i;
float f;
char str[20];
} data;
Page 54 of 57
Programming for Problem Solving Using ‘C’ Unit-IV
Now, a variable of Data type can store an integer, a floating-point number, or a string of characters. It
means a single variable, i.e., same memory location, can be used to store multiple types of data. You
can use any built-in or user defined data types inside a union based on your requirement.
The memory occupied by a union will be large enough to hold the largest member of the union. For
example, in the above example, Data type will occupy 20 bytes of memory space because this is the
maximum space which can be occupied by a character string. The following example displays the total
memory size occupied by the above union −
#include <stdio.h>
#include <string.h>
union Data
{
int i;
float f;
char str[20];
};
int main( )
{
union Data data;
printf( "Memory size occupied by data : %d\n", sizeof(data));
return 0;
}
When the above code is compiled and executed, it produces the following result −
Memory size occupied by data : 20
Accessing Union Members
To access any member of a union, we use the member access operator (.). The member access
operator is coded as a period between the union variable name and the union member that we wish to
access. You would use the keyword union to define variables of union type. The following example
shows how to use unions in a program −
#include <stdio.h>
#include <string.h>
union Data
{
int i;
float f;
char str[20];
Page 55 of 57
Programming for Problem Solving Using ‘C’ Unit-IV
};
int main( )
{
union Data data;
data.i = 10;
data.f = 220.5;
strcpy( data.str, "C Programming");
printf( "data.i : %d\n", data.i);
printf( "data.f : %f\n", data.f);
printf( "data.str : %s\n", data.str);
return 0;
}
When the above code is compiled and executed, it produces the following result −
data.i : 1917853763
data.f : 4122360580327794860452759994368.000000
data.str : C Programming
Here, we can see that the values of i and f members of union got corrupted because the final value
assigned to the variable has occupied the memory location and this is the reason that the value
of str member is getting printed very well.
Now let's look into the same example once again where we will use one variable at a time which is the
main purpose of having unions −
#include <stdio.h>
#include <string.h>
union Data
{
int i;
float f;
char str[20];
};
int main( )
{
union Data data;
data.i = 10;
Page 56 of 57
Programming for Problem Solving Using ‘C’ Unit-IV
X
R a md a s K a p ila
A s s is t a n t P ro f e s s o r , N S R IT
Page 57 of 57