Module 4
Module 4
struct student{
char first[10]; Declaration is terminated by a semicolon.
No variable has actually been created.
char midinit;
Only the form of the data has been defined.
char last[20];
};
1. Structure declaration
• This declaration creates a
struct student{ structure variable sname.
char first[10]; • It contains 3 members.
char midinit; • When a structure variable is
declared, the compiler
char last[20]; automatically allocates sufficient
}; memory to accommodate all of
its members.
struct student sname;
Members
struct Student {
char name[50];
int roll;
};
int main() {
struct Student s;
printf("Enter Student name and Roll no");
scanf("%s", s.name);
scanf("%d", &s.roll);
printf("\nStudent Details:\n");
printf("Name: %s\n", s.name);
printf("Roll Number: %d\n", s.roll);
return 0; }
Structure declaration/memory allocation
struct addr
{
char name[30];
char street[40];
char city[20];
char state[3];
};
That's why we use s->age += 1; with pointers—to modify the original structure
directly.
Basic Structure with a Pointer
#include <stdio.h> int main() {
struct Student s;
int id = 101;
struct Student {
s.p = &id; // Assign address of 'id'
char name[50];
to pointer
int age;
printf("Student ID: %d\n", *s.p);
float marks;
return 0;
int *p; // Pointer inside the }
structure
};
Union
A union in C is a special data type that allows
different variables to share the same memory
location.
d.i = 10;
#include <stdio.h> printf("i: %d\n", d.i);
#include <stdio.h>
union Example {
int x; // 4 bytes
double y; // 8 bytes (largest member)
char c; // 1 byte
};
int main() {
printf("Size of union: %lu bytes\n", sizeof(union Example));
return 0;
}
Union vs Structure
Feature struct union
Memory Allocation Separate memory for each Shared memory for all
member members