0% found this document useful (0 votes)
24 views

Unit-4 Structure

Structures in C are used to group together related data of different types under one name. A structure allows the creation of user-defined data types that can contain multiple members of different data types. Structures are helpful for storing information about multiple entities where each entity has attributes of varying data types. For example, a student entity may have attributes like name (string), roll number (int) and marks (float). Structures provide a cleaner way to store such related data as compared to separate arrays. The struct keyword is used to define a structure, which contains member variables of different data types. Structure variables can then be declared to access the member variables using dot operators.

Uploaded by

cartoon hub
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views

Unit-4 Structure

Structures in C are used to group together related data of different types under one name. A structure allows the creation of user-defined data types that can contain multiple members of different data types. Structures are helpful for storing information about multiple entities where each entity has attributes of varying data types. For example, a student entity may have attributes like name (string), roll number (int) and marks (float). Structures provide a cleaner way to store such related data as compared to separate arrays. The struct keyword is used to define a structure, which contains member variables of different data types. Structure variables can then be declared to access the member variables using dot operators.

Uploaded by

cartoon hub
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

Structure

Q.Why is Structure used?

very helpful in cases where we need to store similar data of multiple entities

Structures (also called structs) are a way to group several related variables into one
place. Each variable in the structure is known as a member of the structure.

Unlike an array, a structure can contain many different data types (int, float, char,
etc.). In C, there are cases where we need to store multiple attributes of an entity. It
is not necessary that an entity has all the information of one type only. It can have
different attributes of different data types. For example, an entity Student may
have its name (string), roll number (int), marks (float). To store such type of
information regarding an entity student, we have the following approaches:

o Construct individual arrays for storing names, roll numbers, and marks.
o Use a special data structure to store the collection of different data types.

#include<stdio.h>
void main ()
{
char names[2][10],dummy; // 2-
dimensioanal character array names is used to store the names of the students
int roll_numbers[2],i;
float marks[2];
for (i=0;i<3;i++)
{

printf("Enter the name, roll number, and marks of the student %d",i+1);
scanf("%s %d %f",&names[i],&roll_numbers[i],&marks[i]);
scanf("%c",&dummy); // enter will be stored into dummy character at each iterat
ion
}
printf("Printing the Student details ...\n");
for (i=0;i<3;i++)
{
printf("%s %d %f\n",names[i],roll_numbers[i],marks[i]);
}
}

Output

Enter the name, roll number, and marks of the student 1Arun 90 91
Enter the name, roll number, and marks of the student 2Varun 91 56
Enter the name, roll number, and marks of the student 3Sham 89 69

Printing the Student details...


Arun 90 91.000000
Varun 91 56.000000
Sham 89 69.000000

The above program may fulfill our requirement of storing the information of an
entity student. However, the program is very complex, and the complexity increase
with the amount of the input. The elements of each of the array are stored
contiguously, but all the arrays may not be stored contiguously in the memory. C
provides you with an additional and simpler approach where you can use a special
data structure, i.e., structure, in which, you can group all the information of
different data type regarding an entity.

Q. What is structure in C?
 The structure in C is a user-defined data type that can be used to group
items of possibly different types into a single type.
 Structure-function can be used to write code effectively
 A structure is a custom data type that holds multiple members of different
data type under a single unit
 Unlike an array, a structure can contain many different data types (int, float,
char, etc.).
Structure in c is a user-defined data type that enables us to store the collection of
different data types. Each element of a structure is called a member. Structures ca;
simulate the use of classes and templates as it can store various information

The ,struct keyword is used to define the structure. Let's see the syntax to define
the structure in c.

1. struct structure_name
2. {
3. data_type member1;
4. data_type member2;
5. .
6. .
7. data_type memeberN;
8. };

Let's see the example to define a structure for an entity employee in c.

1. struct employee
2. { int id;
3. char name[20];
4. float salary;
5. };

The following image shows the memory allocation of the structure employee that
is defined in the above example.
Here, struct is the keyword; employee is the name of the structure; id, name,
and salary are the members or fields of the structure. Let's understand it by the
diagram given below:

Advantages Of Structures:

1. Heterogeneous collection of data items: structure allows us to create user


defined data-type which can store items with different data types. For
example, if we want to store students' records with their roll number, name,
marks and address then it comprises items with different types i.e. roll
number can be of integer number type, name is of string type, marks is
floating number type and address is of string type.
In C, it can be achieved by using structure like this:
struct student
{
int roll_number;
char name[30];
float marks;
char address[50];
};

Now structure variables can be created using struct student s1, s2; and these
variables can store all the details of two students.

2. Reduced complexity: think of storing student records of five different


students with roll number, name, marks and address like in above example
without structure! What do we need here? Five integer type variables for
storing roll number of five students, five string variables for storing name of
five students, five floating type variables for storing marks, and again five
string variables for storing address of five students. Terrible! Don’t do it that
way! Just create structure and create an array of structure. That’s it!
Here is simple setup for doing that:

struct student
{
int roll_number;
char name[30];
float marks;
char address[50];
};

struct student s[5];


3. Increased productivity: structure in C eliminates lots of burden while
dealing with records which contain heterogeneous data items, thereby
increasing productivity.
4. Maintainability of code: using structure, we represent complex records by
using a single name, which makes code maintainability like a breeze.
5. Enhanced code readability: code readability is crucial for larger projects.
Using structure code looks user friendly which in turn helps to maintain the
project.
6. Suitable for some mathematical operations: by using basic data-types we
can not represent complex numbers, distances (feet-inch system), times
(hour-minute-second system). Mathematical operations like adding complex
numbers, or subtracting them; adding two distances in a feet-inch system;
finding the difference between two time periods in an hour-minute-second
system can be done effectively using the concept of structure.
Here is simple setup for dealing with complex numbers:

struct complex
{
float real;
float imaginary;
};

struct complex c1, c2, sum;

Check C program to add two complex number using Structure and C


program to add two distance in feet-inch system for real world
examples.

Defining a Structure:
Define structure in C

Structure variables must first be defined before being created. Structures may be
defined using the struct keyword.
Syntax:-

struct name_of_the_structure

data_type member1;

data_type member2;

...

data_type memberN;

};

Example of C Structures

struct bill

float amount;

int id;

char address[100];

};

How to Declare structure variable?

To make it simple to access a structure member, we can create a variable for the
structure. Structure variables can be declared in one of two ways:

1. By using the struct keyword in the main() method.


2. By declaring a variable when the structure is defined.
1st way:
Let’s look at an example of using the struct keyword to define structure variable.
Declaring it within the main function is appropriate.

struct employee

{ int id;

char name[50];

float salary;

};

Put the provided code within the main() method at this point.

struct employee e1, e2;

The values kept in the structure can be accessed using the variables e1 and e2.
Here, e1 and e2 may be handled similarly to Java and C++ objects.

2nd way:
Let’s see a different approach to declaring variables as the structure is being
defined.

struct employee

{ int id;

char name[50];

float salary;

}e1,e2;

Which strategy is best?


Use the first method if some variables are not fixed. You have the freedom to
declare the structure variable several times.
Use the second strategy if the number of variables is fixed. Declaring a variable in
the main() method saves you code.

Accessing members of the structure

There are two ways to access structure members:

1. By . (member or dot operator)


2. By -> (structure pointer operator)

Let’s look at the code for the (member) operator to access the id member of the p1
variable.
p1.id

How to initialize a structure variable?


C language supports multiple ways to initialize a structure variable. You can use
any of the initialization method to initialize your structure.

 Initialize using dot operator


 Value initialized structure variable
 Variant of value initialized structure variable

Initialize structure using dot operator

In C, we initialize or access a structure variable either through dot . or arrow -


> operator. This is the most easiest way to initialize or access a structure.

Example:

// Declare structure variable


struct student stu1;

// Initialize structure members


stu1.name = "Pankaj";
stu1.roll = 12;
stu1.marks = 79.5f;
Copy

Value initialized structure variable

The above method is easy and straightforward to initialize a structure variable.


However, C language also supports value initialization for structure variable.
Means, you can initialize a structure to some default value during its variable
declaration.

Example:

// Declare and initialize structure variable


struct student stu1 = { "Pankaj", 12, 79.5f };
Copy

Note: The values for the value initialized structure should match the order in
which structure members are declared.
Invalid initialization:

// Declare and initialize structure variable


struct student stu1 = { 12, "Pankaj", 79.5f };
Copy

The above code will throw compilation error. Since the order of member type in
structure is character array, integer finally float. But, we aren’t initializing the
structure variable in the same order.

Variant of value initialized structure variable

The above approach may suit all needs. In addition, C language supports flexibility
to initialize structure members in any order. I know this sounds bit confusing. As,
just now I said C will throw error if you try to initialize members in different order
of declaration.

This approach is an extension of above. Here, you can specify member name along
with the value.

Example:
// Declare and initialize structure variable
struct student stu1 = {
.roll = 12,
.name = "Pankaj",
.marks = 79.5f
};
Copy

Structure default initialization

Default initialization of a variable considered as good programming practice.


However, C doesn’t support any programming construct for default structure
initialization. You manually need to initialize all fields to 0 or NULL.

Initializing all fields to NULL is bit cumbersome process. Let’s do a small hack to
initialize structure members to default value, on every structure variable
declaration.

Example:

// Define macro for default structure initialization


#define NEW_STUDENT { "", 0, 0.0f }

// Default initialization of structure variable


struct student stu1 = NEW_STUDENT;
Copy

Program to declare, initialize and access structure

/**
* How to declare, initialize and access structures in C language
*/

#include <stdio.h>

// Macro for default student structure initialization


#define NEW_STUDENT { "", 0, 0.0f }
// Student structure type declaration
struct student
{
char name[100];
int roll;
float marks;
};

int main()
{
// Declare structure variable with default initialization
struct student stu1 = NEW_STUDENT;

// Read student details from user


printf("Enter student name: ");
gets(stu1.name);

printf("Enter student roll no: ");


scanf("%d", &stu1.roll);

printf("Enter student marks: ");


scanf("%f", &stu1.marks);

// Print student details


printf("\n\nStudent details\n");
printf("Name : %s\n", stu1.name);
printf("Roll : %d\n", stu1.roll);
printf("Marks: %.2f\n", stu1.marks);

return 0;
}
O/P-

Enter student roll no: 12


Enter student marks: 79.5

Student details

Name : Pankaj Prakash

Roll : 12

Marks: 79.50

Accessing Structure Members:

You might also like