Arrays allow to define type of variables that can hold several data items of the same kind. Similarly structure is another user defined data type available in C that allows to combine data items of different kinds.
Structures are used to represent a record. Suppose you want to keep track of your books in a library. You might want to track the following attributes about each book −
- Title
- Author
- Subject
- Book ID
Defining a Structure
struct <name>
{
member definition;
member definition;
...
member definition;
} [one or more structure variables];
struct Books
{ char title[50];
char author[50];
char subject[100];
int book_id;
} book;
Structure Variables
struct Person
{
// code
};
int main()
{
struct Person person1, person2, p[20];
return 0;
}
Another way to define Structure Variables
struct Person
{
// code
} person1, person2, p[20];
Using typedef
struct Distance
{
int feet;
float inch;
};
int main()
{
struct Distance d1, d2;
}
{typedef struct Distance
int feet;
float inch;
}distances;
int main()
{
distances d1, d2;
}
Example
#include <stdio.h>
#include <string.h>
struct Person {
char name[50];
int citNo;
float salary;
} person1;
int main() {
strcpy(person1.name, "George Orwell");
person1.citNo = 1984;
person1. salary = 2500;
printf("Name: %s\n", person1.name);
printf("Citizenship No.: %d\n", person1.citNo);
printf("Salary: %.2f", person1.salary);
return 0;
}
Nested Structure
struct complex {
int imag;
float real;
};
struct number {
struct complex comp;
int integers;
} num1, num2;
Accessing The Nested Structure Variable
num2.comp.imag = 11;