Unlock the complete
Logicmojo experience for FREE
Sign Up Using
1 Million +
Strong Tech Community
500 +
Questions to Practice
50 +
Jobs Referrals
Sign Up Using
Strong Tech Community
Questions to Practice
Jobs Referrals
We already have int, char, float, and double data types defined in C to hold integers, characters, and decimal values.(also known as the primitive data types). We also have some derived data types, such as arrays and strings, to store elements of comparable data types together. Arrays and strings, on the other hand, can only store variables of comparable data types, whereas strings can only store characters. What if we need to store two distinct data types in C together for a large number of objects? For example, a pupil variable may have a name, class, section, and so on.
So, if we want to store all of its information, we can make separate variables for each variable, such as a character array for the name, an integer variable for the class, and a character variable for the section. However, this solution is a little sloppy; C gives us with a more neat and clean solution, namely, Structure.
The structure in C represents a user-defined datatype that enables us to combine data of various types. Structure aids in the creation of a more meaningful complicated data type. It is comparable to an Array, but an array only holds data of the same type. Structure, on the other hand, can store data of any sort, making it more practical.
The structure in C is a datatype which is User-defined that is used to connect two or more data categories or data structures. We can build a structure for a student that has the following data types: a character array for storing name, an integer for storing roll number, and a character for storing section, and so on. Structures do not take up any memory space unless and until we specify some variables for them. When we specify its variables, they consume memory space that varies depending on the type of data member and alignment.
The keyword struct is used to describe a structure. The data type struct is defined as a collection of main and derived data types.
struct tag_name { Datatype member_name1; Datatype member_name2; Datatype member_name2; }[one or more structure variables];
Struct Keyword :- When defining a structure in C, the keyword struct is used at the beginning of the code. A structure, like a union, begins with a term.
tag_name :-This is the structure's tag name, which is given after the keyword struct.
Datatype :-The data type specifies the nature of the structure's data components. A structure can contain data members of various data kinds.
member_name :-This is the name of the structure's data component. A structure can contain any amount of data members. Each data member is assigned its own memory area.
We can name one or more structure variables after the closing curly brace, which is optional.
In the structure type declaration, the final curly brace must be followed by a semicolon(;).
Assume you want to save information about an individual, such as his or her name, department, and salary. To keep this information, you can use variables such as name, department, and salary.
What if you need to save data for more than one person? You must now create separate variables for each piece of information for each person: name1, department1, salary1, name2, department2, salary2, and so on.
A better strategy would be to group all related information into a single Person structure and use it for all people.
Lets Understand why we use Struct In C, with and an example.
Let's see the example to define a structure in C for a student.
struct Student { int rollno; char name[10]; float marks; };
This struct type Student declares a structure to store a student's information. This structure contains 3 data fields: name, rollno, and marks. Structure members or elements are the names given to these sections. Every element may have a unique datatype. For example, in this instance, the name is an array of the char type, the rollno is an int type, etc. Student is the name of the structure and is called as the structure Name tag.
Let's interpret it using the following diagram:
The memory allocation for the structure employee depicted in the above example can be seen in the next picture.
A structure's variables can be declared either as part of the structure defining process or after the structure has been established. Declaring a structure variable is equivalent to declaring a regular variable of any other datatype. The two methods listed below can be used to define structure variables:
When there are only a few variables to be stated, this method of declaring a structure variable is appropriate.
struct Student { int rollno; char name[10]; float marks; }st1, st2;
The structure variables are stated just before the structure is terminated at the conclusion of the structure definition. st1 and st2 are the elements of the structure Student in the example above. rollno, name, and marks will each be given a distinct copy of the structure's data members.
When numerous variables need to be declared, this method of creating structure variables is preferred. Outside of the structure, the variables are defined.
struct Student { int rollno; char name[10]; float marks; }; int main() { struct Student st1, st2; // structure variables; }
The struct keyword must be mentioned before the structure name when the structure variables are declared in the main() function. st1 and st2 are the elements of the structure student in the example above.
Like other variables, structure members cannot be initialised within the structure specification. This is so because memory is not yet allocated to a structure's data members when it is created. Only when a structure variable is defined is memory allocated.
struct Student { int rollno = 7; // COMPILER ERROR: cannot initialize members here char name[10] = {"Akash"} ; // COMPILER ERROR: cannot initialize members here float marks = 50; // COMPILER ERROR: cannot initialize members here };
When the structure's data elements are initialised inside the structure, a compilation error will be raised. Make a structure variable to initialise the data component of the structure. This variable has access to every component of the framework and has the ability to change its values. Take a look at the sample below, which uses structure variables to initialise a structure's members.
Simple lack of memory allocation when a datatype is defined is the cause of the aforementioned error. Only when variables are made does memory get allocated. Curly braces, or "," can be used to initialise structure elements. The setup that follows, for instance, is acceptable.
struct Student { int rollno; char name[10]; float marks; }; int main() { struct Student st1, st2; // structure variables; st1.rollno = 7 strcpy(st1.name,"Akash"); st1.marks = 50 }
In the preceding example, the structure variable st1 is modifying the structure's data members. st1 has distinct access to the data members in the form of a copy. Any additional structure variable will receive a copy of the name, rollno, and marks and be able to alter it.
Members of a structure in C can be accessed and given values in a variety of ways. Structure members have no significance apart from the structure. To give a value to any structure member, the member name must be linked with the structure variable via the dot(.) operator, also known as the period or member access operator.
#include<stdio.h
> #include<string.h
> struct Student { int rollno; char name[10]; float marks; }; int main() { struct Student st1; /* s1 is a variable of Student type and age is a member of Student */ st1.rollno = 7; strcpy(st1.name, "Akash"); st1.marks = 50; printf("Name of Student 1: %s\n", st1.name); printf("Roll number of Student 1: %d\n", st1.rollno); printf("Marks of Student 1: %f\n", st1.marks); return 0; }
Name of Student 1: Akash Roll number of Student 1: 7 Marks of Student 1: 50.000000
To make an alias name for data types, we use the typedef keyword. It is frequently used with structures to simplify variable declaration syntax.
struct rectangle{ int length; int breath; }; int main() { struct rectnagle r1, r2; }
We can create an equivalent code with a simpler syntax using typedef:
typedef struct rectangle{ int length; int breath; } rectangles; int main() { rectangles r1, r2; }
#include <stdio.h
> #include <string.h
> // struct with typedef rectangle typedef struct rectangle { int length; int breath; } rectangle; int main() { rectangle r1; r1.length = 19; r1.breath = 25; // print struct variables printf("Length Of rectangle is : %d\n", r1.length); printf("Breath Of rectangle is: %d\n", r1.breath); return 0; }
Length Of rectangle is : 19 Breath Of rectangle is: 25
To make an alias rectangle, we used typedef in conjunction with the rectangle structure. We can now easily declare a rectangle variable with the alias, rectangle r1.
A structure can be passed as a method argument in the same way that any other variable or pointer can.
#include#include struct Student { int rollno; char name[10]; float marks; }; void studentInfo( struct Student st ); int main( ) { struct student st1; struct student st2; int rollno = 7; strcpy( st1.name, "Akash"); float marks = 50; int rollno = 8; strcpy( st2.name, "Amit"); float marks = 60; studentInfo( st1 ); studentInfo( st2 ); return 0; } void studentInfo( struct student st ) { printf( "Student Roll no is : %d\n", st.rollno); printf( "Student Name is : %s\n", st.name); printf( "Marks of Student is : %f\n", st.marks); }
Designated initialization is a basic initialization of structure members that is typically used when we only want to initialise a few structure members rather than all of them.
We can see that we use curly braces, and data members are read and initialised in between them using the dot operator. We can initialise any number of structure components from a single structure, and they are all separated by commas. The most essential aspect, however, is that we can initialise members in any order. It is not necessary to keep the members in the same sequence as they are listed in the structure.
#include <stdio.h
>
// creating a structure
struct Student
{
int rollno;
char name[10];
float marks;
};
int main ()
{
// creating a structure variable and initialzing some of its members
struct Student st1 = {.name = 'Akash', .rollno = 7};
printf("Name Of student1 is: %c\n",st1.name);
printf("Roll no of Student1 is: %d\n",st1.rollno);
}
We can see in the preceding example that we have only initialised two members of the structure. It is also worth noting that they are not initialised in the sequence in which they were declared in the structure.
Name of Student 1: Akash Roll number of Student 1: 7
Assume you need to keep student information in your database, such as name, class, and roll number. The first thing that comes to mind is to make a structure variable and access the student information. This method is only practical for a few students, but what if the overall number of students is 100? Creating 100 distinct structure variables for 100 students is inconvenient. In such situations, an array of structures is used.
An array of structures can be declared in the same way that other data kinds (mostly primitive) can. An collection of structures behaves similarly to a regular array. To access an array element, however, the name of the structure followed by the dot operator(.) and the name of the array must be stated.
#include <stdio.h
>
// creating a structure
struct Student
{
int rollno;
char name[10];
float marks;
};
struct Student st[5];
int i, j;
void ask()
{
for(i = 0; i < 3; i++)
{
printf("\nEnter %dst Student Information:\n", i+1);
printf("\nStudent name:\t");
scanf("%s", st[i].name);
printf("\nEnter Rollno:\t");
scanf("%d", &st[i].rollno);
}
printf("\nDisplaying Student Information:\n");
for(i = 0; i < 3; i++)
{
printf("\nStudent name is %s", st[i].name);
printf("\nRollno is %d", st[i].rollno);
}
}
void main()
{
ask();
}
Enter 1st Student Information: Student name: Akash Enter Rollno: 7 Enter 2st Student Information: Student name: Adhar Enter Rollno: 9 Enter 3st Student Information: Student name: Amit Enter Rollno: 10
Displaying Student Information: Student name is Akash Rollno is 7 Student name is Adhar Rollno is 9 Student name is Amit Rollno is 10
In the preceding example, we built the structure Student, which stores student names, rollno and marks. We've created a three-dimensional array st to hold the names and rollno of three pupils. It is worth noting that, unlike the standard array in C, the array of structures in C is initialised by using the structure names as a header.
A pointer structure in C is a variable that contains the address of the structure's memory block. It is comparable to other pointer variables such as an int pointer or a float pointer.
#include<stdio.h
> struct point { int a, b; }; int main() { struct point var1 = {5, 6}; // var2 is a pointer to structure var1. struct point *var2 =&var1
; // Accessing data members of myStruct using a structure pointer. printf("%d %d", var2->a, var2->b); return 0; }
5 6
Variable var1 is present in the structure myStruct in the preceding rxample. The pointer variable var2 holds the location of this structure variable.
The term "nested" refers to the act of placing or storing one thing inside another. Because structure in C is a user-defined data type, we can specify another structure as its data member when creating a structure, resulting in a structure with another structure inside it. The nested structure can also have stacked structures.
struct structure_1 { datatype1 member_name1; datatype2 member_name2; }; struct structure_2 { datatype member_name; .... .... struct structure_1 structure_1_variable_name; };
#include <stdio.h
>
struct Student
{
char name[20];
char parentsname[30];
int rollno;
struct studentinfo
{
char address[10];
char subject[10];
int age;
}
studentinfo;
};
int main()
{
struct Student st;
printf("Student Adrress is :");
scanf("%s",st.studentinfo.address);
printf("Student Subject is :");
scanf("%s",st.studentinfo.subject);
printf("Student age is :");
scanf("%d",st.studentinfo.age);
printf("Student name is :");
scanf("%s",st.name);
printf("Student parentsName is :");
scanf("%s",st.parentsname);
printf("Student Rollno is:");
scanf("%d",st.rollno);
return 0;
}
Student name is :Akash Student parentsName is :Gopal Student Rollno is:7 Student Adrress is :Agra Student Subject is :Maths Student age is :17
The logic and data members are identical to those in the prior example. The main difference here is that we built an embedded structure rather than a separate structure of class details. You can see that, despite the fact that the methods are distinct, the results are identical.
We know that memory is allocated to a structure variable as soon as it is defined, based on the variable's data type. A structure is made up of various data members, so if they are not correctly aligned, memory will be wasted. We give them proper alignment (i.e., proper order) by defining them in decreasing order of memory capacity to minimise memory waste caused by random declaration of data members.
#includestruct StructureNameA { char ch1; short sh1; int in1; double dbl1; float fl1; } structA; struct StructureNameB { double dbl1; int in1; char ch1, ch2; } StructB; struct StructureNameC { float fl2; short sh1; char ch2, ch3; } structC; int main() { // printing the size of both structures printf("Size of StructureNameA is: %lu\n",sizeof(structA)); printf("Size of StructureNameB is: %lu\n",sizeof(structB)); printf("Size of StructureNameC is: %lu\n",sizeof(structC)); }
Size of StructureNameA is: 24 Size of StructureNameB is: 16 Size of StructureNameC is: 8
By this time in the article, you should have a good idea of how important and useful structures in C are. Structures, like everything else that has some benefits, have some limitations. In this part, we will go over some of these limitations
The struct data structure is not a built-in data type. The compiler will throw an error if you attempt to use it as a built-in data type.
Arithmetic operators cannot be used with structure variables.
Structures do not allow for data hiding. Structure in C does not enable any data members to be hidden and all functions have access to them.
In C, you cannot specify member functions within a structure. Structure in C only permits the definition of data members within it and forbids the definition of functions.
The notion of access modifiers does not exist in C. As a result, data members in a structure are always accessible to all methods outside of that structure.
Static members and constructors cannot be created within the core of a structure in C.
To summarize, you learned the fundamentals of a structure in C programming in this essay Structure in C Programming. You began with a brief introduction to a structure in C before moving on to explore its applications. Following that, you learned about structure syntax, how to define and initialise a structure in C, and how to access the elements of a structure in C. Moving on, you learned about other essential ideas in the Structure in C Programming article, such as designated initialization of a structure in C, array of structures, and a pointer to a structure. You concluded the essay with a brief explanation of nested structures and structure limitations in C.
Good luck and happy learning!