C Structure
Syntax
struct [structure tag] {
member definition;
member definition;
...
} [one or more structure variables];
Example
#include <stdio.h>
#include <string.h>
// Declare a structure with members
struct Person {
char name[50];
int age;
};
int main() {
// Declare and initialize structure variable
struct Person person1;
strcpy(person1.name, "John Doe");
person1.age = 35;
// Print structure members
printf("Person Name: %s\n", person1.name);
printf("Person Age: %d\n", person1.age);
return 0;
}
Output
The output of the above example will be:
Person Name: John Doe
Person Age: 35
Explanation
In C, a structure is a user-defined composite data type that groups together related data items of different types. A structure can contain variables, arrays, and other structures as its members. It is defined using the struct
keyword followed by the structure tag and a set of member definitions.
Use
Structures are widely used in C for the following purposes:
- Storing related data items together
- Passing a collection of data items as a single argument to a function
- Representing complex data structures, such as trees and graphs
- Creating data types that can be easily customized and extended
Important Points
- A structure is a user-defined composite data type in C.
- The
struct
keyword is used to define a structure. - A structure can contain variables, arrays, and other structures as its members.
- A structure can have one or more variables of its type.
- Structure members can be accessed using the dot (.) operator.
- Structure variables can be initialized using the curly braces ({}) syntax.
- To declare a structure variable, the structure tag must be followed by the variable name, separated by a space.
Summary
A structure in C is a user-defined composite data type that can group together related data items of different types. It can be used for storing related data items together, passing a collection of data items as a single argument to a function, representing complex data structures, and creating custom data types. Understanding the syntax and use cases for structures can greatly enhance the readability, functionality, and flexibility of your C programs.