0% found this document useful (0 votes)
3 views39 pages

Module 2b

The document provides an overview of structures and unions in C programming, detailing their definitions, syntax, and various operations such as accessing members, initializing, and using arrays within structures. It also covers advanced topics like nested structures, pointers to structures, and self-referential structures, which are crucial for implementing complex data structures like linked lists. Additionally, the document illustrates how to pass structures to functions and return them, emphasizing the importance of memory management.

Uploaded by

moksheshveera
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views39 pages

Module 2b

The document provides an overview of structures and unions in C programming, detailing their definitions, syntax, and various operations such as accessing members, initializing, and using arrays within structures. It also covers advanced topics like nested structures, pointers to structures, and self-referential structures, which are crucial for implementing complex data structures like linked lists. Additionally, the document illustrates how to pass structures to functions and return them, emphasizing the importance of memory management.

Uploaded by

moksheshveera
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Structure and Union

Structures- array of structures - nested structures - structures with


functions - self-referential structures - bit fields - pointers to structures,
Unions- comparison with structures.
Structure
• A structure is a user-defined data type that can be used to group
items of possibly different types into a single type. The struct keyword
is used to define a structure.
• Syntax of Structure
• Structure Definition
• Creating Structure Variables

2
Structure Definition Creating Structure Variable

struct structure_name { struct strcuture_name var;


data_type1 member1;
data_type2 member2; Or

}; struct structure_name {

}var1, var2….;

3
struct Person struct Person
{ {
char name[50]; char name[50];
int id; int id;
float salary; float salary;
}; }p1;

int main()
{ struct Person p1;
return 0;
}
4
Keyword typedef
• We use the typedef keyword to create an alias name for data types. It is
commonly used with structures to simplify the syntax of declaring
variables.
// struct with typedef person
typedef struct Person {
char name[50];
int id;
float salary;
} person;

// create Person variable


person p1;
5
Basic Operations of Structure
• Access Structure Members
• structure_name . member1;
• strcuture_name . member2;

• If we have a pointer to the structure, we can also use the arrow


operator to access the members.
• structure_ptr -> member1
• structure_ptr -> member2

6
Initialize Structure Members
• struct structure_name str;
• str.member1 = value1;
• ….

• struct structure_name str = {value1, value2, value3 ….};

• struct structure_name str = { .member1 = value1, .member2 = value2,


.member3 = value3 };

7
Array within a Structure
• An array can be declared inside a structure as a member when we
need to store multiple members of the same type.
• Syntax:
struct StructureName {
// Other members
dataType arrayName[arraySize];
};
• Accessing Elements of an Array within a Structure
[Link][index]

8
struct student{
char name[20];
int roll;
float marks[5]; /* This is array within structure */
};
int main(){
struct student s;
int i;
float sum=0, p;
printf("Enter name and roll number of students:\n");
scanf("%s%d",[Link], &[Link]);
printf("\nEnter marks obtained in five different subject\n");
for(i=0;i< 5;i++) {
printf("Enter marks:\n");
scanf("%f",&[Link][i]);
sum = sum + [Link][i];
}
p = sum/5;
printf(“Student records and percentage is:\n”);
printf("Name : %s\n", [Link]);
printf("Roll Number : %d\n", [Link]);
printf("Percentage obtained is: %f", p);
return 0;
}
9
Array of Structures
• to store several structures of the same type in a single array.

struct student
{
char stu_name[30];
float cgpa;
int age;
char reg_no[10];
};
struct student s[70];
10
#include <stdio.h>
#include <string.h> // Traversing through the array of structures
// Structure definition //and displaying the data
struct Student { for (int i = 0; i < 3; i++) {
printf("Student %d:\n", i+1);
char name[50]; printf("Name: %s\n", students[i].name);
int age; printf("Age: %d\n", students[i].age);
float marks; printf("Marks: %.2f\n", students[i].marks);
}; }
return 0;
int main() { }
// Declaration and initialization of an array of structures
struct Student students[3] = {
{"Nikhil", 20, 85.5},
{"Shubham", 22, 90.0},
{"Vivek", 25, 78.0}
};
11
#include <stdio.h>
#include <string.h> // Traversing through the array of structures
// Structure definition //and displaying the data
struct Student { for (int i = 0; i < 70; i++) {
char name[50]; printf("Student %d:\n", i+1);
int age; printf("Name: %s\n", students[i].name);
printf("Age: %d\n", students[i].age);
float marks;
printf("Marks: %.2f\n", students[i].marks);
}; }
int main() { return 0;
// Declaration and initialization of an array of structures }
struct Student students[70];
for (int i=0;i<70;i++){
scanf(“%s”, students[i].name);
scanf(“%d”, &students[i].age);
scanf(“%f”, &students[i].marks);
}
12
Structure within Structures
• Nested Structure
• One of the elements in the definition of a struct type is
of another struct type.
• Syntax
struct struct1{
type var1;
type var2;
struct struct2 strvar;
}

13
int main()
{
Example struct employee e1 = {"Kiran", 25000, {12, 5, 1990}};
printf("Name: %s\n", [Link]);
#include <stdio.h> printf("Salary: %f\n", [Link]);
printf("DoB: %d-%d-%d\n", e1.d1.d, e1.d1.m, e1.d1.y);
#include <string.h> return 0;
struct dob{ }
int d, m, y; struct dob d1 = {12, 5, 1990};
}; struct employee e1 = {"Kiran", 25000, d1};
struct employee{ struct employee{
char name[10]; char name[10];
float salary; float salary;
struct dob{
struct dob d1; int d, m, y;
}; } d1;
14
};
Structure Pointer - Pointers to Structures
• A structure pointer is a pointer variable that stores the address of a
structure.
• Define a new derived data type using the "struct" keyword.
• Declare a structure variable of this derived data type.
• Declare a pointer variable and store the address of previously
declared structure variable.
• To access the elements of a structure with pointer, we use a special
operator called the indirection operator ->

15
#include <stdio.h>
struct Student {
int id; Structure Pointer - Pointers to Structures
char name[20];
};
int main() {
struct Student s;
struct Student *ptr;
ptr = &s; // pointer points to structure
printf("Enter student ID: ");
scanf("%d", &ptr->id);
printf("Enter student name: ");
scanf("%s", ptr->name);
printf("\nStudent Details:\n");
printf("ID: %d\n", ptr->id); // printf("ID: %d\n", (*ptr).id);
printf("Name: %s\n", ptr->name); //printf("Name: %s\n", (*ptr).name);
return 0;
16
}
/* Reading student details */
#include <stdio.h> for (i = 0; i < n; i++)
#include <stdlib.h> {
struct Student printf("Roll number: ");
{ scanf("%d", &s[i].roll);
int roll; printf("Name: ");
char name[30]; scanf("%s", s[i].name);
float marks; printf("Marks: ");
}; scanf("%f", &s[i].marks);
int main() }
{ /* Displaying student details */
struct Student *s; printf("\n--- Student Details ---\n");
int n, i; for (i = 0; i < n; i++)
printf("Enter number of students: "); {
scanf("%d", &n); printf("Roll: %d\n", s[i].roll);
/* Dynamic memory allocation */ printf("Name: %s\n", s[i].name);
s = (struct Student *)malloc(n * sizeof(struct Student)); printf("Marks: %.2f\n", s[i].marks);
}
if (s == NULL)
{ /* Free allocated memory */
free(s);
printf("Memory allocation failed\n");
return 1; return 0;
} 17
}
for (i = 0; i < n; i++)
#include <stdio.h> {
#include <stdlib.h> /* Reading student details */
struct Student printf("Roll number: ");
{ scanf("%d", &(s + i)->roll);
int roll; printf("Name: ");
char name[30]; scanf("%s", (s + i)->name);
float marks; printf("Marks: ");
}; scanf("%f", &(s + i)->marks);
int main() }
{ /* Displaying student details */
struct Student *s; for (i = 0; i < n; i++)
int n, i; {
printf("Enter number of students: "); printf("Roll: %d\n", (s + i)->roll);
scanf("%d", &n); printf("Name: %s\n", (s + i)->name);
/* Dynamic memory allocation */ printf("Marks: %.2f\n", (s + i)->marks);
s = (struct Student *)malloc(n * sizeof(struct Student)); }
/* Free allocated memory */
if (s == NULL) free(s);
{
return 0;
printf("Memory allocation failed\n"); }
return 1;
18
}
for (i = 0; i < n; i++) /* Reading student details */
#include <stdio.h> {
#include <stdlib.h> printf("Roll number: ");
struct Student scanf("%d", &(s)->roll);
{ printf("Name: ");
int roll; scanf("%s", (s )->name);
char name[30]; printf("Marks: ");
float marks; scanf("%f", &(s)->marks);
}; s++;
int main() }
{ s=temp;
struct Student *s,*temp; for (i = 0; i < n; i++) /* Displaying student details */
int n, i; {
printf("Enter number of students: "); printf("Roll: %d\n", (s)->roll);
scanf("%d", &n); printf("Name: %s\n", (s)->name);
/* Dynamic memory allocation */ printf("Marks: %.2f\n", (s)->marks);
s = (struct Student *)malloc(n * sizeof(struct Student)); s++;
if (s == NULL) }
{ /* Free allocated memory */
printf("Memory allocation failed\n"); free(temp);
return 1; temp=NULL;
} return 0;
temp=s; }
19
Structures and Functions

20
#include <stdio.h>
struct rectangle{
float len, brd; How to Pass Struct Elements
};
void area(float a, float b){
double ar = (double)(a*b);
printf("Length: %f \nBreadth: %f \nArea: %lf\n", a, b, ar);
}
int main(){
struct rectangle r;
printf("Enter length and breadth\n");
scanf("%f%f",&[Link],&[Link]);
area([Link], [Link]);
return 0;
}

21
#include <stdio.h>
struct rectangle{
float len, brd; How to Pass Struct Variable
double a;
};
void area(struct rectangle r1){
r1.a = (double)([Link]*[Link]);
printf("Length: %f \nBreadth: %f \nArea: %lf\n", [Link], [Link], r1.a);
}
int main(){
struct rectangle r;
printf("Enter length and breadth\n");
scanf("%f%f",&[Link],&[Link]);
area(r);
return 0;
}

22
#include <stdio.h>
struct rectangle {
float len, brd; How to return Struct Variable
double a;
};
struct rectangle area(float x, float y){
double ar = (double)(x*y);
struct rectangle r1 = {x, y, ar};
return r1;
}
int main(){
struct rectangle r;
float x, y;
printf("Enter length and breadth\n");
scanf("%f%f",&x,&y);
r = area(x, y);
printf("Length: %f \n Breadth: %f \n Area: %lf\n", [Link], [Link], r.a);
return 0;
} 23
#include <stdio.h>
struct rectangle{
float len, brd; How to Pass Struct Variable
double a;
}; by a reference
void area(struct rectangle *r1){
r1 -> a = (double)(r1 -> len * r1 -> brd);
printf("Length: %f \nBreadth: %f \nArea: %lf\n", r1->len, r1->brd, r1->a);
}
int main(){
struct rectangle r;
printf("Enter length and breadth\n");
scanf("%f%f",&[Link],&[Link]);
area(&r);
return 0;
}

24
#include <stdio.h>
struct rectangle{
float len, brd; How to Pass Struct pointer
double a;
};
void area(struct rectangle *r1){
r1 -> a = (double)(r1 -> len * r1 -> brd);
printf("Length: %f \nBreadth: %f \nArea: %lf\n", r1->len, r1->brd, r1->a);
}
int main(){
struct rectangle r, *rp;
rp = &r;
printf("Enter length and breadth\n");
scanf("%f%f",&[Link],&[Link]);
area(rp);
return 0;
}

25
#include <stdio.h>
#include <stdlib.h>
struct rectangle{ How to Pass Struct pointer
float len, brd;
double a;
};
void area(struct rectangle *r1){
r1 -> a = (double)(r1 -> len * r1 -> brd);
printf("Length: %f \nBreadth: %f \nArea: %lf\n", r1->len, r1->brd, r1->a);
}
int main(){
struct rectangle *rp;
rp=(struct rectangle *)malloc(sizeof(struct rectangle));
printf("Enter length and breadth\n");
scanf("%f%f",&rp->len,&rp->brd);
area(rp);
return 0;
}
26
#include <stdio.h>
struct rectangle {
How to return Struct pointer
➢ r1 is created on the stack
float len, brd;
➢ It exists only while the function is executing
double a;
➢ When area() finishes, r1 is destroyed
};
➢ The returned pointer points to invalid memory
struct rectangle * area(float x, float y){
double ar = (double)(x*y);
static struct rectangle r1; // Static ensures the object remains in memory after function exits
[Link] = x; [Link] = y; r1.a = ar;
return &r1;
}
int main (){
struct rectangle *r;
float x, y;
printf("Enter length and breadth\n");
scanf("%f%f",&x,&y);
r = area(x, y);
printf("Length: %f \n Breadth: %f \n Area: %lf\n", r->len, r->brd, r->a);
return 0;
}
27
Self-referential Structures
• A self-referential structure is a struct data type in C, where one or
more of its elements are pointer to variables of its own type.
• They are extensively used to build complex and dynamic data
structures such as linked lists and trees.
strut typename{
type var1;
type var2;
... ...
struct typename *var3;
}
28
#include <stdio.h>
struct Node {
int data;
struct Node *next; // self-referential pointer
};
int main() {
struct Node n1, n2;
[Link] = 10;
[Link] = &n2; // n1 points to n2
[Link] = 20;
[Link] = NULL; // last node
printf("First node data: %d\n", [Link]);
printf("Second node data: %d\n", [Link]->data);
return 0;
}

29
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node *next; // self-referential pointer
};
int main() {
struct Node *head, *second;
// Allocate memory
head = (struct Node *)malloc(sizeof(struct Node));
second = (struct Node *)malloc(sizeof(struct Node));
// Assign values
head->data = 10;
head->next = second;
second->data = 20;
second->next = NULL;
// Access data
printf("First node data : %d\n", head->data);
printf("Second node data : %d\n", head->next->data);
// Free memory
free(head);
free(second);
return 0; 30
#include <stdio.h>
#include <stdlib.h>

struct Node { // Traversal


int data; temp = head;
struct Node *next; printf("Linked List Elements:\n");
};
int main() {
struct Node *head, *second, *third, *temp; while (temp != NULL) {
// Allocate memory printf("%d -> ", temp->data);
head = (struct Node *)malloc(sizeof(struct Node)); temp = temp->next;
second = (struct Node *)malloc(sizeof(struct Node)); }
third = (struct Node *)malloc(sizeof(struct Node)); printf("NULL\n");

// Assign data and links // Free memory


head->data = 10; free(head);
head->next = second;
free(second);
second->data = 20;
second->next = third; free(third);
third->data = 30;
third->next = NULL; return 0;
}
31
Bit Fields
• Bit fields allow us to store data in individual bits inside a structure
instead of using full bytes or words.

struct structure_name {
data_type member_name : number_of_bits;
};

32
#include <stdio.h>
struct Normal {
unsigned int a;
unsigned int b;
unsigned int c;
};
int main() {
printf("Size of Normal structure: %lu bytes\n", sizeof(struct Normal));
return 0;
}
#include <stdio.h>
struct BitField {
unsigned int a : 1;
unsigned int b : 1;
unsigned int c : 1;
};
int main() {
printf("Size of BitField structure: %lu bytes\n", sizeof(struct BitField));
return 0;
}

33
• 1. Memory optimization
• Bit fields allow you to store many boolean or small-range values
inside a single integer.
• 2. Hardware register mapping
• Hardware registers often have specific bits with specific meanings.

34
Union
• Union is a user-defined data type that can contain elements of the
different data types just like structure.
• But unlike structures, all the members in the C union are stored in the
same memory location.
• Due to this, only one member can store data at the given point in
time.

35
#include <stdio.h> #include <stdio.h>

// Declaring multiple unions // Declaring multiple structures


union A{ struct SA{
int x; double x; Structures use padding to satisfy
alignment requirements.
char y; char y; The structure size must be a
}; }; multiple of the largest data type
alignment inside it.
union B{ struct SB{
int arr[10]; int arr[10];
char y; char y;
}; };

int main() { int main() {


printf("Sizeof A: %ld\n", sizeof(union A)); printf("Sizeof A: %ld\n", sizeof(struct SA));
printf("Sizeof B: %ld\n", sizeof(union B)); printf("Sizeof B: %ld\n", sizeof(struct SB));
return 0; return 0;
} }
36
#include <stdio.h> #include <stdio.h>
union utest { struct stest {
int x, y; int x, y;
}; };

int main(){ int main(){


union utest ut; struct stest st;
printf("Address of union x is %p\n",&ut.x); printf("Address of struct x is %p\n",&st.x);
printf("Address of union y is %p\n",&ut.y); printf("Address of struct y is %p\n",&st.y);
ut.x = 2; st.x = 2;
printf("x = %d, y = %d\n", ut.x, ut.y); printf("x = %d, y = %d\n", st.x, st.y);
ut.y = 10; st.y = 10;
printf("x = %d, y = %d\n\n", ut.x, ut.y); printf("x = %d, y = %d", st.x, st.y);
return 0; return 0;
} }

37
#include <stdio.h>
union utest {
int x;
char y;
};

int main(){
union utest ut;
printf("Address of union x is %p\n",&ut.x);
printf("Address of union y is %p\n",&ut.y);
ut.x = 2;
printf("x = %d, y = %d\n", ut.x, ut.y);
ut.y = 'a';
printf("x = %d, y = %d\n\n", ut.x, ut.y);
return 0;
}

38
• 1. Memory-efficient data storage
When a variable can take one of many data types, but not all at the
same time.
• 2. Implementing variant data types (tagged data)
Often combined with a struct to indicate what type of data is currently
stored.

39

You might also like