C Structures: Definitions and Examples
C Structures: Definitions and Examples
Structure - Nested structures – Pointer and Structures – Array of structures – Example Program using
structures and pointers – Self referential structures – Dynamic memory allocation - Singly linked list -
typedef.
Structure Definition :
A structure in C is that allows you to combine multiple variables of different data types under a single name.
Example:
Student: name, roll no, mark, avg
Book: author, title, price, year
Address: door no, street name, place, state, pin
Difference b/w Arrays and Structures:
Arrays Structures
Collection of similar data types. Collection of different data types.
Static memory allocation is done in arrays Dynamic memoryallocation is done in structures.
It uses index or subscript to access It uses (.) dot operator and ->(pointer) operator to
an array element. access members of structures
Array is a pointer to its first element. Structure is not a pointer.
Array is a derived data type. Structure is a user defined data type.
Accessing array element takes less time Accessing structure member takes more time.
It has no keywords. It uses keyword “struct”
Structure Definition
Structure definition means creating a new user-defined datatype using the keyword `struct` to group
different data types. Note: semicolon }; in the ending line is must.
Steps :
1. Declaring structure
2. Declaring structure variable
3. Initializing the members of the structure
4. Accessing the members of structure
1. Declaring structure:
Syntax: Example:
struct tag_name struct student
{ {
datatype member 1; char name[10];
datatype member 2; int roll_no;
float percentage;
‘
datatype member n; };
};
2. Structure Declaration
NESTED STRUCTURE:
Definition
● A nested structure is a structure that contains another structure as its member. It is used when
one record has another record inside it. which means A structure with in a structure is
called nested structure.
● The elements of nested structure are accessed using dot (.) operator
3. Memory is allocated when the outer structure variable is created, including memory for the inner
structure.
#include <string.h>
struct Inner {
}; int pincode;
struct Outer { };
}; int id;
};
int main() {
printf("%s\n", [Link]);
printf("%d\n", [Link]);
printf("%s\n", [Link]);
printf("%d\n", [Link]);
return 0;
Output:
Ravi
101
Chennai
600001
Syntax:
structure tagname_1 Example:
{ struct Employee
data_type member1; {
data_type member2; char ename[20];
data_type member3; int empid;
.. int salary;
member n; struct date
structure tagname_2 {
{ int day;
data_type member_1; int month;
data_type member_2; int year;
data_type member_3; }doj;
... }emp;
member_n;
} var1; Syntax:
} var2;
outrstructurevariable . innerstructure variable .
innerstructuremember
ARRAY OF STRUCTURES:
Definition:
Example:
* Multiple students
* Multiple employees
* Multiple books
struct StructureName {
data_type member1;
data_type member2;
};
#include<stdio.h>
Enter name: Ravi
struct student
Enter roll no: 101
{
Enter marks: 89.5
char name[20];
int roll_no, i;
Enter details of student 2
float marks;
};
Enter name: Kavi
int main()
Enter roll no: 102
{
Enter marks: 92.0
struct student s[5];
int i;
Enter details of student 3
for(i = 0; i <5; i++)
{
Enter name: Mani
printf("\n Enter details of student %d\n\n",
i+1); Enter roll no: 103
Enter marks: 88.0
int roll;
char name[20];
float marks;
};
int main() {
};
return 0;
● A pointer to a structure is a pointer variable that stores the address of a structure variable.
● It is used to access structure members through a pointer using the arrow operator (`->`).
struct Student s;
Two ways:
1. Using `(*ptr).member`
(*ptr).roll
(*ptr).marks
ptr->roll
ptr->name
ptr->marks
#include <string.h>
float marks;
};
int main() {
ptr = &s;
return 0;
struct Student {
int roll;
float marks;
};
int main() {
p->roll = 101;
p->marks = 95.5;
return 0;
Definition
A pointer to an array of structures is used when we want to access structure elements using pointers
instead of normal array indexing.
* Faster access
Syntax
p = s; // Equivalent to p = &s[0]
101 89.50
};
int main() {
{101, 89.5},
{102, 92.0},
{103, 88.0}
};
return 0;
}; 103 88.00
int main() {
struct Student s1 = {101, 89.5};
struct Student s2 = {102, 91.0};
struct Student s3 = {103, 88.0};
ptr[0] = &s1;
ptr[1] = &s2;
ptr[2] = &s3;
printf("Roll\tMarks\n");
return 0;
}
Dynamic Memory Allocation (DMA) in C allows you to allocate memory at runtime, not at compile time.
* malloc → garbage
* realloc → resize
#include <stdlib.h>
Syntax
Features
Example
int main() { 10
int n, *p; 20
30
10 20 30
printf("\nYou entered:\n");
return 0;
Purpose
Syntax
Features
* Memory initialized to 0
Example
int main() { 10
int n, *p; 15
scanf("%d", &n); 5 10 15
scanf("%d", &p[i]);
printf("\nYou entered:\n");
free(p);
return 0;
3. realloc() – Reallocation
Purpose
Syntax
Features
* Used to increase or decrease memory size
Example
#include <stdio.h> 10 20 30 40
#include <stdlib.h>
int main() {
int *p;
p[0] = 10;
p[1] = 20;
p[2] = 30;
p[3] = 40;
free(p);
return 0;
}
4. free() – Release memory
Purpose
Syntax
free(ptr);
Features
C Program to generate Salary Slip of employee( Dynamic memory allocation for Structure
using pointers):
#include <stdio.h> Output:
#include<stdlib.h> enter the number of employee2
struct employee enter the nameravi
{ Enter Basic Salary (RS): 12000
char name[10];
int basic, da, hra, ta, others; Enter Hra1000
int pf,it,t;
int net_salary; Enter da500
}e[10];
int main() Enter TA500
{
int i,n; Enter Others1000
struct employee *ptr;
printf("enter the number of employee"); Enter pf500
scanf("%d",&n);
ptr=(struct employee*)malloc(n * sizeof(struct Enter IT1000
employee)); enter the nameraja
for(i=0;i<n;i++) Enter Basic Salary (RS): 25000
{
printf("enter the name"); Enter Hra1000
scanf("%s",(ptr+i)->name);
printf("Enter Basic Salary (RS): "); Enter da1000
scanf("%d",&(ptr+i)->basic);
printf("\nEnter Hra"); Enter TA1000
scanf("%d",&(ptr+i)->hra);
printf("\nEnter da"); Enter Others500
scanf("%d",&(ptr+i)->da);
printf("\n Enter TA"); Enter pf1000
scanf("%d",&(ptr+i)->ta);
printf("\nEnter Others"); Enter IT1500
scanf("%d",&(ptr+i)->others);
printf("\nEnter pf"); Name is ravi Net Salary is:RS
scanf("%d",&(ptr+i)->pf); 13500
printf("\nEnter IT");
scanf("%d",&(ptr+i)->it); Name is raja Net Salary is:RS
26000
//calculate net salary
(ptr+i)->net_salary = (ptr+i)->basic + (ptr+i)->da +
(ptr+i)->hra + (ptr+i)->ta + (ptr+i)->others - ((ptr+i)->pf+(ptr+i)-
>it);
}
//printing Net salary
for(i=0;i<n;i++)
{
printf("\n Name is %s",(ptr+i)->name);
printf("\t Net Salary is:RS %d\n",(ptr+i)->net_salary);
}
return(0);
}
struct Node {
int data;
struct Node *next; // pointer to same structure type
};
* `next` can store the address of another Node
* This creates a chain of nodes → Linked list
Key Points
o A structure CANNOT contain a variable of same type (infinite size)
o But it CAN contain a pointer to same type (fixed size)
struct Node {
int x;
struct Node *next; // ok (pointer has fixed size)
};
#include <stdio.h> Output
struct Node {
};
int main() {
[Link] = 10;
[Link] = 20;
return 0;
LINKED LIST
A Linked List is a dynamic data structure made of nodes, where each node contains:
1. Data
2. Pointer to the next node
* Insert at end
[Link]
* Delete first node
* Delete last node
* Delete specific value
* Delete at position
[Link]
Print all nodes one-by-one.
Node Creation:
#include <stdio.h> Linked List: 10 -> 20 -> 30 -> NULL
#include <stdlib.h>
struct node {
int data;
};
int main() {
// Assign data
head->data = 10;
second->data = 20;
third->data = 30;
// Link nodes
head->next = second;
second->next = third;
third->next = NULL;
while(temp != NULL) {
temp = temp->next;
printf("NULL\n");
// Free memory
free(head);
free(second);
free(third);
return 0;
} prev = 10;
} current = 20
Second iteration
Next=30
20-> Next=10
Prev=20
30->20->10-null
TYPEDEF
Definition
`typedef` is used in C to give a new name (alias) to an existing data type.
* Makes code easier to read
* Reduces typing for complex types
* Commonly used with **structures, pointers, arrays, function pointers
Syntax
typedef existing_type new_name;
. With Structures
#include <stdio.h> 101 Ravi
typedef struct {
int roll;
char name[20];
} Student;
int main() {
return 0;
1.C program to read, display, add, and Enter first distance (km m): 5 800
subtract two distances. Distance must
bedefined using kms and meters using Enter second distance (km m): 3 500
structures.(typedef)
Difference: 2 km 300 m
typedef struct {
int km;
int m;
} Distance;
int main() {
// Read distances
// Addition
[Link] = [Link] + [Link];
[Link] = [Link] + 1;
// Subtraction
[Link] = [Link] - 1;
// Display
return 0;
int main() {
return 0;
Define Union. Describe how to declare, initialize and accessmembers of Union with a
programming example.
Definition of Union
A union is a user-defined data type in C that allows different variables to share the same memory
location.
At any time, only one member of a union can store a value.
Declaration of a Union
union Example {
int x;
float y;
char ch;
};
Creating (Declaring) Union Variable
union Example e;
Initializing Union
You can initialize a union only one member at a time:
When a new member is assigned, the previous value is overwritten because all members share the
same memory.
printf("%d", e.x);
printf("%f", e.y);
printf("%c", [Link]);
Simple Program Example
#include <stdio.h> Output
char grade;
};
int main() {
union Data d;
[Link] = 101;
return 0;
(ii)Illustrate a C program to store the employee information using Structure and search a
particular employee details.
#include <stdio.h>
#include <string.h>
struct Employee {
int id;
char name[30];
float salary;
};
int main() {
scanf("%d", &n);
printf("ID: ");
scanf("%d", &e[i].id);
printf("Name: ");
scanf("%s", e[i].name);
printf("Salary: ");
scanf("%f", &e[i].salary);
// Search operation
scanf("%d", &searchId);
found = 1;
printf("\nEmployee Found!\n");
break;
if(!found)
return 0;
struct Student {
int roll;
float marks;
};
int main() {
struct Student s = {101, 89.5};
return 0;
}
Explanation
* Function receives simple variables.
* Structure itself is not passed.
* Easy, but if many members → we must pass many arguments.
struct Student {
int roll;
float marks;
};
int main() {
struct Student s1 = {101, 89.5};
return 0;
}
Explanation
* Full structure is passed.
* A copy is created inside the function.
* Changes inside function do NOT affect original structure.
#include <stdio.h>
struct Student {
int roll;
float marks;
};
int main() {
struct Student s1 = {101, 89.5};
return 0;
}
Usage Used when one unit has sub- Used when many units of
units. same type needed.
Memory allocation Memory allocated for nested Memory allocated for each
structure inside parent element of array separately
Flexibility Good for complex, multi-level Good for large sets of simple,
data. repetitive data.