Structure Declaration, Definition, and Initialization in C
1. Structure Declaration:
- Declaring a structure without defining it:
struct Student;
- Declaring and defining a structure with members:
struct Student {
int roll_no;
char name[50];
float marks;
};
2. Structure Definition:
- Defining a structure and initializing its members:
struct Student {
int roll_no;
char name[50];
float marks;
};
struct Student s1; // Declaration of structure variable
3. Structure Initialization:
- Static Initialization:
struct Student s1 = {101, "John", 85.5};
- Dynamic Initialization:
struct Student s1;
s1.roll_no = 101;
strcpy([Link], "John");
[Link] = 85.5;
- Using `struct` keyword for Initialization:
struct Student s1 = {.roll_no = 101, .marks = 85.5, .name = "John"};
- Nested Structure Initialization:
struct Address {
char city[50];
char state[50];
};
struct Student {
int roll_no;
char name[50];
struct Address address;
};
struct Student s1 = {101, "John", {"Hyderabad", "Telangana"}};
- Pointer Initialization:
struct Student *s1;
s1 = (struct Student*)malloc(sizeof(struct Student));
s1->roll_no = 101;
strcpy(s1->name, "John");
s1->marks = 85.5;
4. Anonymous Structure:
- Using an anonymous structure (without a name):
struct {
int roll_no;
char name[50];
float marks;
} s1 = {101, "John", 85.5};
5. Array of Structures:
- Declaring and initializing an array of structures:
struct Student {
int roll_no;
char name[50];
float marks;
};
struct Student students[2] = {
{101, "John", 85.5},
{102, "Alice", 90.0}
};
6. Pointer to Structure:
- Using a pointer to access structure members:
struct Student {
int roll_no;
char name[50];
float marks;
};
struct Student s1 = {101, "John", 85.5};
struct Student *ptr = &s1;
printf("%d %s %.2f", ptr->roll_no, ptr->name, ptr->marks);