Introduction to Structure in C
In simple words, a structure is a user-defined data type in C. With structures we can combine various data types to store a specific type of data. A structure helps us to store a complex data type in a more meaningful way. It is somewhat similar to an array. The only difference is that an array is used to store a collection of homogeneous data types whereas a structure can store a collection of heterogeneous types of data.
For example, we need to store the information about students like his/her name, Roll number and marks. We can store theat information separately. A structure gives us a way to store the collection of that information in one unit under one name since all that information is related to the student.
The keyword struct defines structures.
Syntax of Structures
- struct Structure_name
- {
- data_type member1;
- data_type member2;
- data_type memeber;
- };
We can create the structure for a person as said above as:
- struct student
- {
- char Name[50];
- int Roll_no;
- int Marks;
- };
When we define a structure, it only creates a user-defined type, but no memory is allocated. For memory allocation we need to declare variables of our structure type. For the preceding structure of student, a variable can be declared as:
If we need an array then we can declare an array of students as:
Or we can also use:
- struct student
- {
- char Name[50];
- int Roll_no;
- int Marks;
- }
- s1, s2, s[20];
Accessing members of a structure
We can access the members of a structure in either of the following two ways.
- Member/Period operator(.)
- Structure pointer operator(->)
Any member of a structure can be accessed as: structure_name.memberName. Suppose we want to access marks of s2 then that would be s2.marks.
The pointer operator we will discuss later in this article.
Structures within Structures
Structures can be nested within other structures in C programming. Suppose we need to store a student address with student data. So we can modify the preceding structure as in the following:
- struct address
- {
- char[50] locality;
- char[50] city;
- int pincode;
- };
- struct student
- {
- char Name[50];
- int Roll_no;
- int Marks;
- struct address add;
- } ;
- student s1, s2;
We can access locality for the s2 structure variable as:
Passing Structure by value
A structure variable can be passed to the function as an argument as a normal variable. If a structure is passed by value then changes made in structure variable in the function is not reflect in the original structure variable in the calling function.
- void show(struct student st)
- {
- printf("nStudent Name is :%s",st.Name);
- printf("n Roll No is: %d",st.Roll_no);
- }
Accessing Structure Members with Pointers
When we have a pointer of structure type, we must an arrow -> to access its members.
- int main()
- {
- struct student st;
- struct student* ptr = &st;
- ptr->name = "Ratnesh";
- ptr-> Roll_no = 500;
- }