Defining structures in C language
A structure is a user-defined data type in the C programming language that enables us to put together data objects of various data kinds under a single name. A more ordered and practical way to express a complicated data type is through structures.
Basic syntax of structure:
struct structure_name {
data_type1 member1;
data_type2 member2;
...
data_typen membern;
};
Example:
struct person {
char name[50];
int age;
char address[100];
};
In the above example, we have defined a structure named person with three members: name, age, and address. The name and address members are character arrays of size 50 and 100, respectively, and the age member is an integer.
Once a structure is defined, we can declare variables of that structure type, just like any other data type:
struct person p1, p2;
We can then access the members of the structure using the dot (.) operator:
strcpy(p1.name, "John");
p1.age = 30;
strcpy(p1.address, "123 Main St");
In the above example, we have assigned values to the name, age, and address members of the p1 variable of the person structure type using the strcpy and assignment operators.
Example:
#include <stdio.h>
#include <string.h>
struct person {
char name[50];
int age;
float salary;
};
int main() {
struct person p1;
// Assigning values to structure members
strcpy(p1.name, "John");
p1.age = 32;
p1.salary = 5000.50;
// Printing structure members
printf("Name: %s\n", p1.name);
printf("Age: %d\n", p1.age);
printf("Salary: %f\n", p1.salary);
return 0;
}
Output:
Name: John
Age: 32
Salary: 5000.500000