Home »
C programming language
Initialize a struct in accordance with C programming language
In this tutorial, we will learn about how to create and initialize a struct in c programming language?
Submitted by Shubh Pachori, on July 11, 2022
A struct is a keyword that creates a user-defined datatype in the C programming language. A struct keyword creates datatypes that can be used to group items of possibly different types and same types into a single datatype.
For example, if an administration wants to create a file for their students to handle their information they can construct a structure by using the struct keyword because as we know that a student's name is a character value and its roll number and marks are integer values. Hence, it is a problem to store them in the same datatype, but the struct allows you to do the same using it.
Syntax to construct a structure using struct keyword
struct Student{
int roll_no;
char name[30];
};
Here, the struct is a keyword, Student is a tag name, roll_no and name are its members.
Using the struct keyword, we can create a workspace for any heterogeneous and homogeneous type of data to store and manipulate at a single place.
Here, we are using designated initializer to initialize a structure.
C language code to understand how we can initialize a structure?
#include <stdio.h>
// Creating a Student named structure
typedef struct Student {
// name and roll_no are its member
char name[20];
int rollno;
} Student;
int main()
{
// Declaring two Student type variables
Student s1, s2;
// Initializing 1st Student
s1 = (Student){.name = "shubh", .rollno = 1 };
// Initializing 2nd Student
s2 = (Student){.name = "pachori", .rollno = 2 };
printf("\n%d %s\n", s1.rollno, s1.name);
printf("\n%d %s\n", s2.rollno, s2.name);
return 0;
}
Output:
1 shubh
2 pachori
But if we want to input values by the keyboard then we have to use a different method for it.
Here is an example of how we can input values in a structure using a keyboard go through with the below code.
#include <stdio.h>
// Creating a Student named structure
typedef struct Student {
// name and roll_no are its member
char name[20];
int rollno;
} Student;
int main()
{
// Declaring two Student type variables
Student s1, s2;
// Data input through keyboard of s1
printf("Enter Roll Number First Student: ");
scanf("%d", &s1.rollno);
printf("Enter Name First Student: ");
scanf("%s", s1.name);
// Data input through keyboard of s2
printf("Enter Roll Number Second Student: ");
scanf("%d", &s2.rollno);
printf("Enter Name Second Student: ");
scanf("%s", s2.name);
printf("\n%d %s\n", s1.rollno, s1.name);
printf("\n%d %s\n", s2.rollno, s2.name);
return 0;
}
Output:
Enter Roll Number First Student: 101
Enter Name First Student: Subh
Enter Roll Number Second Student: 102
Enter Name Second Student: Pranit
101 Subh
102 Pranit