Unit 4-1
Unit 4-1
Text Books
1. Balagurusamy. E, ―Programming in ANSI C, Tata McGraw Hill, 8thEdition,2019.
2. YashvantKanetkar, ―Let us C‖, BPB Publications, 16th Edition, 2017
3. Herbert Schildt,‖ C: The Complete Reference‖, McGraw Hill, FourthEdition,2014
Reference Books
Structure
A structure is a collection of one or more variables of different data types, grouped together under
a single name. It is derived data type to be arranged in a group of related data items of different data
types. It is a user defined data type because user can decide the data types to be included in the structure
body. By using structures we can make a group of variables, arrays and pointers. Moreover, it is a
convenient tool for handling a group of logically related data items.
Difference between Array and Structure
Array Structure
// Driver code
int main()
{
// Structure variable of organisation
struct Organisation org;
printf("%ld", sizeof(org));
}
Case 2: // Driver code
int main()
// C program to implement {
// the above approach struct Organisation org;
#include <stdio.h>
#include <string.h> // Print the size of organisation
// structure
printf("The size of structure organisation : %ld\n",
// Declaration of the main sizeof(org));
// structure
struct Organisation org.emp.employee_id = 101;
{ strcpy(org.emp.name, "Robert");
char organisation_name[20]; org.emp.salary = 400000;
char org_number[20]; strcpy(org.organisation_name,“xxxxxxxxx");
strcpy(org.org_number, "GFG123768");
// Printing the details
// Declaration of the dependent printf("Organisation Name : %s\n",
// structure org.organisation_name);
struct Employee printf("Organisation Number : %s\n",
{ org.org_number);
int employee_id; printf("Employee id : %d\n",
char name[20]; org.emp.employee_id);
printf("Employee name : %s\n", Output:
int salary; The size of structure organisation : 68
org.emp.name);
printf("Employee Salary : %d\n", Organisation Name : xxxxxxxx
// variable is created which acts org.emp.salary); Organisation Number : GFG123768
// as member to Organisation structure. } Employee id : 101
Employee name : Robert
} emp; Employee Salary : 400000
};
Passing structure to a function
C language supports the passing of structures to functions as an argument.The general form of syntax for
structures to functions is as given below
Whenever a structure element is required to pass to any function,it is essential to declare the structure
outside the main() function,i.e global.Generally they can perform in three ways.
1.Passing structure members to function
2.Passing entire structures to function
3.Passing structure to a function by address
1.Passing structure members to function
In this each member of the structure is passed as an actual argument of the function call.The method is
not efficient when the structure size is large.
//Program to pass a structure to a function
#include<stdio.h>
struct student
{
int rno;
float perc;
};
main()
{
struct student s1;
printf(“enter rollno”);
scanf(“%d”,&s1.rno);
printf(“enter percentage”);
scnf(“%d”,&s1.perc);
display(s1.rno,s1.perc);
}
display(int a,float b)
{
printf(“Rol no is %d”,a);
printf(“Percentage is %f”,b);
return 0;
}
Output
2.Passing entire structures to a function
In this,the entire copy of the structure is passed to the called function.Since this works only on the copy,any
changes to structure members within the functions will not affect the original structure. This method is not
supported by the compilers.
//Program to return the entire structure to the calling function
#include<stdio.h>
struct student
{
int rno;
float perc;
};
main()
{
struct student s1;
printf(“enter rollno”);
scanf(“%d”,&s1.rno);
printf(“enter percentage”);
scnf(“%d”,&s1.perc);
display(s1);
}
display(struct student s2) //value of s2=s1
{
printf(“Rollno is %d”,s2.rno);
printf(“Percentage is %f”,s2.perc);
return 0;
}
3.Passing Structure to a Function by Address
In this,the whole structure is passed to another function by address. It means only the address of the
structure is passed to another function. The whole structure is not passed to another function with all
members an their values. So, this structure can be accessed from called function by its address. This
method is more efficient compared to the previous method.
#include<stdio.h>
struct student
{
int rno;
float perc;
};
main()
{
struct student s1;
printf(“enter rollno”);
scanf(“%d”,&s1.rno);
printf(“enter percentage”);
scnf(“%d”,&s1.perc);
display(& s1);
}
display(struct student *p)
{
printf(“Rollno is %d”,p->rno);
printf(“Percentage is %f”,p->perc);
return 0;
}
User defined datatype
Enumerated data type
We known that words speak more than numbers(as pictures speak more than words)
For example we may use integers 1,2,3,….12 to represent month for easy programming.
It is more readable and understandable if we replace these numbers by some meaningful and descriptive
names such as Jan,Feb,…..,Dec.
This concept of replacing integers by some descriptive names gives rise to new data type called numerated
type.
An enumerated data type is a user defined data type which can take the integer values from a list.
These integer values are replaced by meaningful and descriptive names so as to enhance the
readability of the program.
These descriptive names are called enumerators or enumerator constants.
Declaring an enumerated data type
To declare an enumerated type,its identifiers and its values must be declared.Because it is derived from
integer type,its operations are the same as for integers.
Syntax
enum type_Name
{
member1;
member2;
………
………
};
where,
enum is the keyword which tells the compiler about enumerated type definition.
enum type_Name together represent the user defined data type.
member1,member2… are integer constants but represented using descriptive names.These are called
enumerator constants or enumerators.
The definition terminates with a semicolon.
Example
enum color
{
RED,
BLUE,
GREEN
};
enum color c1,c2;
enum days
{
SUNDAY,
MONDAY,
…….
SATURDAY
}d1;
Assigning values to Enumerated data types.
After an enumerated variable has been declared,we can store values in it. While the compile automatically assigns values to
enumerated types starting with 0,the next values are initilized with a value by adding 1 to previous value. For example, to
set up an enumerated type for the rain status, the following program could be used.
//Program by assining enum datatype
#include<conio.h>
enum status
{
low,medium,high
};
int main()
{
enum status rain;
rain=low;
if(rain==low)
printf(“\n rain status is low %d”,low);
return 0;
}
output
rain stauts is low 0
Self Referential Structures
Self Referential structures are those structures that have one or more pointers which point to the same type of
structure, as their member. In other words, structures pointing to the same type of structures are self-referential in
nature.
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.
Types of Self Referential Structures
1.Self Referential Structure with Single Link #include <stdio.h>
struct node { Output
2.Self Referential Structure with Multiple Links
int data1; 30
Self Referential Structure with Single Link: These char data2; 40
struct node* link;
structures can have only one self-pointer as their
};
member. The following example will show us how to int main()
connect the objects of a self-referential structure with the {
single link and access the corresponding data members. struct node ob1; // Node1
The connection formed is shown in the following figure. // 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;
}
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 { OUTPUT
int data; // Forward links
struct node* prev_link; ob1.next_link = &ob2;
struct node* next_link; ob2.next_link = &ob3; 10 20 30
}; 10 20 30
int main() // Backward links 10 20 30
{ ob2.prev_link = &ob1;
struct node ob1; // Node1 ob3.prev_link = &ob2;
// Initialization
ob1.prev_link = NULL; // Accessing data of ob1, ob2 and ob3 by ob1
ob1.next_link = NULL; printf("%d\t", ob1.data);
ob1.data = 10; printf("%d\t", ob1.next_link->data);
printf("%d\n", ob1.next_link->next_link->data);
struct node ob2; // Node2
// Initialization // Accessing data of ob1, ob2 and ob3 by ob2
ob2.prev_link = NULL; printf("%d\t", ob2.prev_link->data);
ob2.next_link = NULL; printf("%d\t", ob2.data);
ob2.data = 20; printf("%d\n", ob2.next_link->data);
struct node ob3; // Node3 // Accessing data of ob1, ob2 and ob3 by ob3
// Initialization printf("%d\t", ob3.prev_link->prev_link->data);
ob3.prev_link = NULL; printf("%d\t", ob3.prev_link->data);
ob3.next_link = NULL; printf("%d", ob3.data);
ob3.data = 30; return 0;
}
UNIT IV STRUCTURE AND POINTERS 09
Text Books
1. Balagurusamy. E, ―Programming in ANSI C, Tata McGraw Hill, 8thEdition,2019.
2. YashvantKanetkar, ―Let us C‖, BPB Publications, 16th Edition, 2017
3. Herbert Schildt,‖ C: The Complete Reference‖, McGraw Hill, FourthEdition,2014
Reference Books
Syntax of C Pointers
The syntax of pointers is similar to the variable declaration in C, but we use the ( * ) dereferencing operator in the
pointer declaration.
datatype * ptr;
where
ptr is the name of the pointer.
datatype is the type of data it is pointing to.
The above syntax is used to define a pointer to a variable. We can also define pointers to functions, structures,
etc.
How to Use Pointers?
The use of pointers in C can be divided into three steps:
Pointer Declaration
Pointer Initialization
Pointer Dereferencing
1. Pointer Declaration
In pointer declaration, we only declare the pointer but do not initialize it.
To declare a pointer, we use the ( * ) dereference operator before its
name.
Example
int *ptr;
The pointer declared here will point to some random memory address
as it is not initialized. Such pointers are called wild pointers.
2. Pointer Initialization
Pointer initialization is the process where we assign some initial value
to the pointer variable. We generally use the ( & ) addressof
operator to get the memory address of a variable and then store it in
the pointer variable.
Example
int var = 10;
int * ptr;
ptr = &var;
We can also declare and initialize the pointer in a single step. This
method is called pointer definition as the pointer is declared and
initialized at the same time.
Example
int *ptr = &var;
void Point()
{
int var = 10;
// declare pointer variable
int *ptr;
// note that data type of ptr and var must be same
ptr = &var;
// assign the address of a variable to a pointer
printf("Value at ptr = %d \n", ptr);
printf("Value at var = %d \n", var);
printf("Value at *ptr = %d \n", *ptr);
}
// Driver program
int main()
{ Output
Point(); Value at ptr = 0x7fff1038675c
return 0; Value at var = 10
} Value at *ptr = 10
Pointer Arithmetic
Pointer Arithmetic is the set of valid arithmetic operations that can be performed on pointers. The pointer variables
store the memory address of another variable. It doesn’t store any value.
Hence, there are only a few operations that are allowed to perform on Pointers in C language. The C pointer
arithmetic operations are slightly different from the ones that we generally use for mathematical calculations. These
operations are:
Data Type Size Description Example
1. Increment/Decrement of a Pointer
Increment: It is a condition that also comes under addition. When a pointer is incremented, it actually increments by the
number equal to the size of the data type for which it is a pointer.
For Example:
If an integer pointer that stores address 1000 is incremented, then it will increment by 4(size of an int), and the new address will
point to 1004. While if a float type pointer is incremented then it will increment by 4(size of a float) and the new address will
be 1004.
Decrement: It is a condition that also comes under subtraction. When a pointer is decremented, it actually decrements by the
number equal to the size of the data type for which it is a pointer.
For Example:
If an integer pointer that stores address 1000 is decremented, then it will decrement by 4(size of an int), and the
new address will point to 996. While if a float type pointer is decremented then it will decrement by 4(size of a float)
and the new address will be 996.