Structures Part 1


Structure is a group of variables of different data types represented by a single name. Lets take an example to understand the need of a structure in C programming.

Lets say we need to store the data of students like student name, age, address, id etc. One way of doing this would be creating a different variable for each attribute, however when you need to store the data of multiple students then in that case, you would need to create these several variables again for each student. This is such a big headache to store data in this way.

We can solve this problem easily by using structure. We can create a structure that has members for name, id, address and age and then we can create the variables of this structure for each student. This may sound confusing, do not worry we will understand this with the help of example.


How to create a structure in C Programming

We use struct keyword to create a structure in C. The struct keyword is a short form of structured data type.


struct struct_name {
   DataType member1_name;
   DataType member2_name;
   DataType member3_name;
   
};

Here struct_name can be anything of your choice. Members data type can be same or different. Once we have declared the structure we can use the struct name as a data type like int, float etc.

First we will see the syntax of creating struct variable, accessing struct members etc and then we will see a complete example.


How to access data members of a structure using a struct variable?

var_name.member1_name;
var_name.member2_name;

How to assign values to structure members?

There are three ways to do this.
1) Using Dot(.) operator

var_name.memeber_name = value;

2) All members assigned in one statement

struct struct_name var_name = 
{value for memeber1, value for memeber2 so on for all the members}

3) Designated initializers – We will discuss this later at the end of this post.

Example of Structure in C

#include <stdio.h>
/* Created a structure here. The name of the structure is
 * StudentData.
 */
struct StudentData{
    char *stu_name;
    int stu_id;
    int stu_age;
};
int main()
{
     /* student is the variable of structure StudentData*/
     struct StudentData student;

     /*Assigning the values of each struct member here*/
     student.stu_name = "Steve";
     student.stu_id = 1234;
     student.stu_age = 30;

     /* Displaying the values of struct members */
     printf("Student Name is: %s", student.stu_name);
     printf("\nStudent Id is: %d", student.stu_id);
     printf("\nStudent Age is: %d", student.stu_age);
     return 0;
}

Output:

Student Name is: Steve
Student Id is: 1234
Student Age is: 30
 
 

Comments