C Structures
Structure is a user-defined datatype in C language which allows us to combine
data of different types together. Structure helps to construct a complex data
type which is more meaningful. It is somewhat similar to an Array, but an array
holds data of similar type only. But structure on the other hand, can store data
of any type, which is practical more useful.
struct keyword is used to define a structure. struct defines a new data type which
is a collection of primary and derived data types.
Syntax:
struct [structure_tag]
//member variable 1
//member variable 2
//member variable 3
...
}[structure_variables];
Example
struct Student
char name[25];
int age;
char branch[10];
// F for female and M for male
char gender;
};
Here struct Student declares a structure to hold the details of a student which
consists of 4 data fields, namely name, age, branch and gender. These fields are
called structure elements or members.
Each member can have different datatype, like in this case, name is an array
of char type and age is of int type etc. Student is the name of the structure and
is called as the structure tag.
Program
#include<stdio.h>
#include<string.h>
struct Student
char name[25];
int age;
char branch[10];
//F for female and M for male
char gender;
};
int main()
struct Student s1;
/*
s1 is a variable of Student type and
age is a member of Student
*/
s1.age = 18;
/*
using string function to add name
*/
strcpy(s1.name, "Viraaj");
/*
displaying the stored values
*/
printf("Name of Student 1: %s\n", s1.name);
printf("Age of Student 1: %d\n", s1.age);
return 0;
assign a value to any structure member, the member name must be
linked with the structure variable using a dot . operator also
called period or member access operator.