0% found this document useful (0 votes)
8 views

Module 4

The document provides an overview of structures and unions in C programming, detailing their declaration, initialization, and usage. It explains how structures can contain arrays, other structures, and how they interact with functions, including passing by value and by pointer. Additionally, it contrasts structures with unions, highlighting their memory allocation and access differences.

Uploaded by

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

Module 4

The document provides an overview of structures and unions in C programming, detailing their declaration, initialization, and usage. It explains how structures can contain arrays, other structures, and how they interact with functions, including passing by value and by pointer. Additionally, it contrasts structures with unions, highlighting their memory allocation and access differences.

Uploaded by

gigachadmaleme
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 33

Module 4

Structure and Union


Declaration, Initialization, Access of Structure
Variables - Arrays of Structure - Arrays within
Structure - Structure within Structures - Structures
and Functions – Pointers to Structure - Unions
Structures

A struct is a group of items


(variables) which may be of different
types.
Structure : terminology
• A structure is a collection of variables referenced under one name.
• provides a convenient means of keeping related information together.
• The members of a structure are logically related.
• Example :
Structure : terminology
• A structure declaration forms a template that can be
used to create structure objects (that is, instances of a
structure).
• The variables that make up the structure are called
members.
• Structure members are also commonly referred to as
elements or fields.
Structures

• Example : struct Student


Singhal
name "V Singhal"
rollno "00CS1001"
classtest 14
midterm 78
final 73
grade B
Structure definition

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 • To access the members of a structure, we


use the member access operator “.”
student{
char sname.midinit = ‘K’;
first[10];
char
midinit;
char
last[20];
};
#include <stdio.h>

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];
};

struct addr ainfo;


#include <stdio.h>
struct sample {
int a;
float b;
char array[20];
}d;
int main() {
printf("%ld", sizeof(struct sample)); 28
return 0;}
2. Structure declaration
struct addr
struct addr
{
{
char name[30];
char name[30];
char street[40]; char street[40];
char city[20]; char city[20];
char state[3]; char state[3];
} ainfo; }
struct addr ainfo;
3. Structure declaration

struct struct addr


{
{
char name[30];
char street[40]; char name[30];
char city[20]; char street[40];
char state[3]; char city[20];
} ainfo; char state[3];
} ainfo;
Arrays of Structures
• Structures are often arrayed.
• An array of structures means multiple instances of a structure stored in
an array format. Each element in the array is a separate structure
object.
• To declare an array of structures, you must first define a structure and
then declare an array variable of that type.
• For example, to declare a 100-element array of structures of type addr
defined earlier, write

struct addr addr_list[100];


// Declaration and initialization using
#include <stdio.h> non-nested
#include <string.h> // initializer list
struct A arr2[2] = { 10, 'A', 20, 'B'
// Structure definition };
struct A {
int var; // Designated initialization
char c; struct A arr3[2] = { {.c = 'A', .var
}; = 10}, {.var = 2, .c = 'b'} };

int main() { printf("%d %c ", arr3[i].var, arr3[i].c);


printf("
// Declaration and initialization using nested ");
// initializer list
struct A arr1[2] = { {1, 'a'}, {2, 'b'} };
return 0;
}
for(int i=0;i<n;i++){
#include<stdio.h>
scanf("%s",item[i].name);
struct details {
scanf("%d",&item[i].quantity);
char name[20];
int price;
scanf("%d",&item[i].price); }
int quantity;
};
for(int i=0;i<n;i++){
int main() {
printf("%s %d\
struct details item[50];
n",item[i].name, item[i].price *
int n; item[i].quantity);
scanf("%d",&n); }
#include <stdio.h>
for (int i = 0; i < 3; i++) {
struct Student {
printf("Name: %s, Roll: %d,
char name[20];
int roll; Marks: %.2f\n", students[i].name,
float marks; students[i].roll, students[i].marks);
};
}
int main() {
struct Student students[3] = { return 0;
{"Alice", 101, 90.5},
}
{"Bob", 102, 85.0},
{"Charlie", 103, 78.3}
}; // Array of structures
Array within a Structure
• An array within a structure means that a structure
contains an array as one of its members.
• This allows a single structure instance to store
multiple values of the same type.
Arrays within a Structure
#include <stdio.h>
printf("Name: %s, Roll: %d\n", s1.name,
struct Student { s1.roll);
char name[20]; printf("Marks: ");
int roll; for (int i = 0; i < 5; i++) {
float marks[5]; // Array inside a printf("%.2f ", s1.marks[i]);
structure }
};
return 0;
int main() { }
struct Student s1 = {"Alice", 101, {90.5,
85.0, 78.3, 88.2, 92.0}};
Key Differences
Feature Array of Structures Array Within a Structure

Definition Multiple instances of a structure A structure containing an


stored in an array. array as a member.

When multiple structure When a structure needs to


Usage variables of the same type are hold multiple values of the
needed. same type.

Storage Each structure object is The array is part of the


independent. structure.
Accessing Members students[i].name, students[i].roll s1.marks[i]

Example Student records for a class. A student’s marks in


different subjects.
Usage
• | Use an array of structures when you have multiple objects with the
same structure.
| Use an array within a structure when a single object needs multiple
related values.
Structure Within Structure
(Nested Structures)
• A structure within a structure (also called nested
structures) is when one structure contains another
structure as its member.
• This helps in organizing complex data in a hierarchical
way.
#include <stdio.h> int main() {
// Initializing an Employee structure
// Defining the nested structures struct Employee emp1 = {"John
struct Address { Doe", 101, {"New York", 10001}};
char city[20];
int pin; // Accessing members
}; printf("Employee Name: %s\n",
emp1.name);
struct Employee { printf("Employee ID: %d\n", emp1.id);
char name[30]; printf("City: %s\n", emp1.addr.city);
int id; printf("Pincode: %d\n", emp1.addr.pin);
struct Address addr;
// Nested structure return 0;
}; }
Structures and Functions
• Using structures with functions allows modularity and better data
organization in C programming. You can pass structures by value, by
reference (using pointers), or return structures from functions.

• Passing Structure to Function (By Value)


• 🔹 When a structure is passed by value, a copy is made, meaning changes
inside the function do not affect the original structure.
#include <stdio.h>
// Defining a structure
struct Student { int main() {
char name[20]; struct Student s1 = {"Alice", 101, 95
int roll;
float marks; // Passing structure to function
};
displayStudent(s1);
// Function that takes structure as an argument
(by value) return 0;
void displayStudent(struct Student s) }
{
printf("Name: %s\n", s.name);
printf("Roll No: %d\n", s.roll);
printf("Marks: %.2f\n", s.marks);
}
Passing Structure by Pointer
(Efficient
#include <stdio.h>
Way) int main() {
struct Student s1 = {"Alice", 19};
// Define structure
struct Student {
char name[50]; printf("Before update: %d\n", s1.age);
int age; updateStudent(&s1); // Pass
}; structure address
// Function to modify student details printf("After update: %d\n", s1.age);
void updateStudent(struct Student *s)
{ return 0;
s->age += 1; // Modify age using }
pointer
}
Why Use -> Instead
of .?
When dealing with pointers to structures, the -> (arrow operator) is used to
access structure members instead of the dot (.) operator.

struct Student s1;


s1.age = 19; // Using . (dot) when structure is NOT a pointer

struct Student *s;


s->age = 19; // Using -> (arrow) when structure is a pointer
Why Use -> Instead
of .?
If we use pass by value instead of pointers:

• This modifies a copy of s1, NOT the original.


• s1.age remains unchanged in main().

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.

Unlike a struct, where each member has its


own memory, in a union all members share
,

the same memory.


- meaning only one member can store a value
at a time.
int main() {
Union union Data d;

d.i = 10;
#include <stdio.h> printf("i: %d\n", d.i);

// Define a union d.f = 5.5;


printf("f: %.2f\n", d.f); // Overwrites i
union Data {
int i; sprintf(d.str, "Hello");
float f; printf("str: %s\n", d.str); // Overwrites f
char str[20];
return 0;
}; }
The size of a union is determined by its largest member.

#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

Access All members can store Only one member stores


values at the same time a value at a time

Size Sum of all members' sizes Size of the largest


member

When multiple values need When storing only one


Use Case value at a time to save
to be stored memory

You might also like