In C, structures allow you to group together variables of different data types under a single name. It's like creating a custom data type. Here's a simple explanation with an example:
#include <stdio.h>
// Define a structure named 'Person'
struct Person {
char name[50];
int age;
float height;
};
int main() {
// Declare a variable of type 'Person'
struct Person person1;
// Assign values to the members of 'person1'
strcpy(person1.name, "John");
person1.age = 30;
person1.height = 6.0;
// Access and print the values
printf("Name: %s\n", person1.name);
printf("Age: %d\n", person1.age);
printf("Height: %.2f\n", person1.height);
return 0;
}
In this example
Person
using the struct
keyword. Inside the structure, we specify members (variables) such as name
, age
, and height
, each with its own data type.main()
function, we declare a variable person1
of type Person
. This variable can hold all the members defined in the Person
structure.person1
using the dot (.
) operator. For example, person1.name
refers to the name
member of the person1
structure, and we use strcpy()
to copy the string "John"
into it..
) operator again.When you run this program, it will print:
Name: John
Age: 30
Height: 6.00
This demonstrates the use of structures in C to group related data together under a single name.