Understanding Structure in C Programming Language

In C, there are various data types available for holding data items. For instance, an array can be used to store data of the same kind, but what if we need to store different data types?

Suppose you want to keep records of the following attributes of sugar patients of XYZ hospital.
Name
Age
Sugar level

Surely we can not hold these data items in an array or others as all the attributes mentioned here are of different data types: string, integer, and float. We can store these data with the following approaches:
I. We can define a separate array for each of the attributes
II. We can store these attributes of different data types using the keyword structure.

Also Read: Preprocessor directives in C Language

The first approach is complex, and its complexity increase with the attributes. The values of each attribute are stored contiguously in the memory but the attribute arrays may not be. This causes difficulty in data access.

As for the latter approach, we can store all the attributes into a single data type. To understand this in detail, let us first understand its basics.



What is a Structure in C Programming Language? 

A structure can be described as a keyword that generates user-defined data types that can be applied to model records. It is a collection of interconnected variables belonging to an object’s theoretically multiple data types. One of the most common and widely used uses of the structure keyword is to define a linked list.

Also Read: What is Program Memory Layout?

In C and C++, there are significant differences in the syntax for defining a structure.
The struct keyword is required in C but optional in C++.

What is a Structure Member in C Language?

The members of a structure are the attributes specified in the entity structure.

Also Read: How to use storage classes in C Language?

In the aforementioned illustration, a patient’s name, age, and blood sugar level are components of a structure called a patient.

How to Define Structure in C?/How to Create Structure in C? 

The structure name and all the characteristics must be used with the struct keyword to define a structure in C. We must first identify the attribute’s data type using the attribute name before defining it.

struct structure_name
{
data_type attribute_1;
data_type attribute_2;
data_type attribute_3;
….
….
….
data_type attribute_n-1;
data_type attribute_n;
};

According to the example taken in this article, our structure is defined as follows:

struct patient
{
char name[10];
int age;
float sugar_level;
};

Here, the struct keyword defines a structure, namely a patient with a name. Let’s see this through the diagram.

When we define structure in a program, no memory is allocated to it. Hence we declare a variable for memory allocation with the defined structure attributes and work with it throughout the remaining program.

 How to Declare Structure Variable in C? 

As we learnt, we declare structure variables to allocate memory and easily access members. It can be declared in two ways.
I. Declaring the variables when defining the structure
II. Declaring separately

To declare a structure variable, we can follow either of the two. Still, method 1 is preferred when the variables needed are knowns. Otherwise, method 2 is a way to go as it provides flexibility to declare the variable numerous times.

Method 1:

           Here we declare the structure variable at the time of structure declaration. 

struct patient

{

char name[10];

int age;

float sugar_level;

}p1, p2;

Method 2:

           Here we declare the structure variable separately inside the main function. 

struct patient

{

char name[10];

int age;

float sugar_level;

};

int main(){

struct patient p1, p2;

}
The structure variables p1 and p2 are used to access the values stored.

How to Initialise a Structure Member in C? 

We already know that declaring a structure does not allocate any memory. Consequently, the execution of the following C programme crashes.

struct patient
{
char name[10] = “Ashish”;
int age = 24;
float sugar_level = 7.8;
};
//compiler error; can not initialise members

However, the following initialisation is acceptable as these members can only be implemented when memory is allocated after declaring variables.

int main(){
struct patient p1 = {“Ashish”, 24, 7.8};
}

Aside from these, a designated initialisation allows members to be initialized in any order. For instance:

int main(){

struct patient p1 = {.name = “Ashish”, .sugar_leve = 7.8, .age = 24};
}

How to Access a Structure Member in C?

We can use the dot operator(.) to access structure members.
p1.name;

Or pointer operator(->).
p1->name;

What is the Need for Structure in C?

A structure is needed to describe more complex records than a single number, character, or boolean information collection. It is a heterogenous user-defined data type that stores different data types in a single data type.

What is the Size of the Structure in C and How to Calculate it?

The size of the structure depends on the members in it. We can consider the members’ size and sum it to calculate it. Let’s see this through an example.

The above example of structure patient has three members, name[10], age, and sugar_level of size 10-byte, 4-byte and 4-byte, respectively. Hence the size of the structure is 10+4+4, i.e. 18 bytes.

sizeof(char) = 1-byte
sizeof(int) = 4-byte
sizeof(float) = 4-byte

Number of characters 10
Size of name character = 10*1 =10-bytes

sizeof(p1) = 10 + 4 + 4 = 18-bytes

Difference between Structure and Union in C Programming with an example.

StructureUnion
A structure is defined by the term “struct.”A union is defined by the term “union.”
A structure’s variables are defined, and the compiler allots memory to each variable member. Each data member’s size plus the size of the structure equals or exceeds the size of the structure.The compiler allocates memory to the largest-size variable member when the variable is defined in the union. The largest data member size in a union determines its size.
Each component of the variable took up its own area in memory.The greatest size variable’s memory is shared by all other variables.
Other variable members won’t be impacted by changing the value of one member.Other members of the variable will be impacted by changing the value of one member.
There will be one evaluation for each variable member.At any one time, just one variable member will be evaluated.
Multiple structural variables can be initialized simultaneously.Only the first data member of the union may be initialized.
At some point in the programme, every member of the variable stores a value.At every given time in the programme, exactly one data member is used to hold a value.
Several variable members can be initialised at once using the structure.One variable member of a union can only be initialised at once.
Values of various data types are stored there.It stores values of various data types one at a time.
Any data member can be retrieved and accessed simultaneously.It permits one data member at a time to be accessed and retrieved.

Advantages of Structure in C

  1. The heterogeneous grouping of data items known as structure enables the storage of several data kinds in a single type.
  2. Consider each member’s characteristics from various angles. The programme is complicated and will be challenging to access. Terrible! We can make programmes simpler by using structure.
  3. Reduces the stress associated with managing heavy records, resulting in an increase in productivity.
  4. Code maintainability is increased since it is straightforward and easily comprehended.
  5. Readability is one of the key components of an effective code. We may simplify detailed records and improve the readability of the code by using structure.
  6. Suitable for a few mathematical procedures.

 Disadvantages of Structure in C

  1. Can increase the complexity of the program
  2. Excessive use of structure makes the program slow
  3. Hard to manage
  4. Difficult error tracking
  5. Beginners find this concept hard to understand

Structure code:

  1. #include
  2. #include
  3. struct patient
  4. {
  5. char name[10];
  6. int age;
  7. float sugar_level;
  8. };
  9. int main( )
  10. {
  11. struct patient p1 = {“Ashish”, 24, 7.8};
  12. //declaring p1 variable for structure and storing first patient information
    1. //printing first patient information
  13. printf( “patient 1 name : %s\n”, p1.name);
  14. printf( “patient 1 name : %f\n”, p1.sugar_level);
  15. return 0;
  16. }

What is the Difference between an Array and a Structure in C?

S.No.ArrayStructure
1.A collection of items with similar data types is referred to as an array.A collection of components with different data types is referred to as a structure.
2. For element access, the array employs subscripts or “[]” (square bracket).“.” (Dot operator) is used by the structure to access elements. "."
3. The size of an array is fixed and equal to the product of the number of elements and the size of each element.The size of the structure is not defined because its individual components might be of various sorts and sizes.
4. The simplest way to declare an array is to use [], without the need for any other keywords.The “struct” keyword is used to create structure declarations.
5. A non-primitive data type is an array.A user-defined datatype is a structure.
6. Searching and traversing an array is quick and simple.Searching and traversal of the structure could be easier and more active.
7.data type array name[size];struct struct_name{ data_type1 ele1; data_type2 ele2;};
8.Array items are kept in adjacent memory regions.The storage of structure elements in a single contiguous memory area is optional.

Conclusion 

We need to hold the data of students getting admission this January. 

Attributes to mention-

Id

Class 

The data items of this entity are composed of different data types. We can neither handle this through generally known data types nor separately, as it must be clarified.

This article addresses scenarios like this and extensively discusses the data type to utilize and how to use it. If you found this post interesting, read our other one.

Frequently Asked Questions (FAQs)

Q1: What is a Structure variable in C? 

Ans: Data elements of various data kinds that are conceptually connected to one another are stored in a single structure with a specified entity that contains their value.

Q2: What is a Nested Structure in C? 

Ans: Ans Just like nested conditions or loop statements, the nested structure is a structure within another structure.

Greetings, My name is Rumi Sadaf. I work as both a content writer and a programmer. In essence, I explain what I know and aid others in understanding programming concepts. Happy Viewing.

Leave a Comment