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

Structures in C

The document provides a comprehensive overview of structures, unions, and enumerations in C programming. It covers defining, declaring, and accessing structures, the differences between structures and unions, and the use of enums for improved code readability. Additionally, it discusses memory allocation, structure padding vs packing, and practical use cases for each data type.
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)
22 views

Structures in C

The document provides a comprehensive overview of structures, unions, and enumerations in C programming. It covers defining, declaring, and accessing structures, the differences between structures and unions, and the use of enums for improved code readability. Additionally, it discusses memory allocation, structure padding vs packing, and practical use cases for each data type.
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
You are on page 1/ 19

Structures in C

1. Defining and Declaring Structures

A structure in C is a user-defined data type that allows grouping variables of


different data types under a single name.

#include <stdio.h>
#include <string.h>

// Define structure
struct Person {
char name[50];
int age;
float height;
};

int main() {
// Declare structure variable
struct Person p1;

// Assign values
p1.age = 25;
p1.height = 5.9;
strcpy(p1.name, "Alice");

// Access values
printf("Name: %s\n", p1.name);
printf("Age: %d\n", p1.age);
printf("Height: %.1f\n", p1.height);
return 0;
}

Output:

Name: Alice
Age: 25
Height: 5.9

2. Accessing Members Using . and -> Operators

• . is used with structure variables.


• -> is used with structure pointers.

#include <stdio.h>
struct Point {
int x, y;
};

int main() {
struct Point p = {10, 20};
struct Point *ptr = &p;

// Using dot operator


printf("x: %d, y: %d\n", p.x, p.y);

// Using arrow operator


printf("x: %d, y: %d\n", ptr->x, ptr->y);
return 0;
}

Output:

x: 10, y: 20
x: 10, y: 20

3. Array of Structures

#include <stdio.h>
struct Student {
int id;
char name[50];
};

int main() {
struct Student s[2] = {
{1, "John"},
{2, "Emma"}
};

for (int i = 0; i < 2; i++) {


printf("ID: %d, Name: %s\n", s[i].id,
s[i].name);
}
return 0;
}
Output:

ID: 1, Name: John


ID: 2, Name: Emma

4. Nested Structures

#include <stdio.h>
#include <string.h>
struct Address {
char city[20];
int pincode;
};

struct Employee {
char name[50];
struct Address addr;
};

int main() {
struct Employee emp;
strcpy(emp.name, "Alice");
strcpy(emp.addr.city, "Mumbai");
emp.addr.pincode = 400001;

printf("Name: %s\n", emp.name);


printf("City: %s\n", emp.addr.city);
printf("Pincode: %d\n", emp.addr.pincode);
return 0;
}

Output:

Name: Alice
City: Mumbai
Pincode: 400001

5. Structure Padding

Structure padding is the addition of empty bytes to align data members according
to the system architecture.

#include <stdio.h>
struct A {
char c;
int i;
};

int main() {
printf("Size of structure A: %lu\n", sizeof(struct
A));
return 0;
}

Output (may vary):

Size of structure A: 8
Unions in C

1. Defining and Using Unions

A union is like a structure but uses shared memory for all members.

#include <stdio.h>
#include <string.h>
union Data {
int i;
float f;
char str[20];
};

int main() {
union Data data;

data.i = 10;
printf("data.i: %d\n", data.i);

data.f = 220.5;
printf("data.f: %.1f\n", data.f); // Overwrites i

strcpy(data.str, "Hello");
printf("data.str: %s\n", data.str); // Overwrites f

return 0;
}
Output:

data.i: 10
data.f: 220.5
data.str: Hello

2. Difference Between Structure and Union

Feature Structure Union


Memory Allocates memory for all members Shares memory for all members
Size Sum of all members' sizes Size of the largest member
Usage Use all members independently One member at a time

Enumerations in C

1. Defining Enums Using enum Keyword

An enum is a user-defined data type consisting of integral constants.

#include <stdio.h>

enum Color {RED, GREEN, BLUE};

int main() {
enum Color c;
c = GREEN;

printf("Color code: %d\n", c); // Outputs 1


return 0;
}

Output:

Color code: 1

2. Accessing Enum Values

You can directly use the enum names.

#include <stdio.h>

enum Days {MON, TUE, WED, THU, FRI, SAT, SUN};

int main() {
enum Days today = FRI;
if (today == FRI) {
printf("Weekend is near!\n");
}
return 0;
}

Output:

Weekend is near!

3. Custom Starting Values

#include <stdio.h>
enum Level {LOW = 10, MEDIUM = 20, HIGH = 30};

int main() {
enum Level l = MEDIUM;
printf("Level value: %d\n", l);
return 0;
}

Output:

Level value: 20

4. Importance of Enums

• Improve code readability


• Restrict variable to hold only certain values
• Useful in switch-case
Structures in C

1. Defining and Declaring Structures


Name: Alice
Age: 25
Height: 5.9
2. Accessing Members Using . and -> Operators
x: 10, y: 20
x: 10, y: 20
3. Array of Structures
ID: 1, Name: John
ID: 2, Name: Emma
4. Nested Structures
Name: Alice
City: Mumbai
Pincode: 400001
5. Structure Padding

(Output will vary by system, typically 8 on 64-bit systems due to padding)

Size of structure A: 8

Unions in C

1. Defining and Using Unions


data.i: 10
data.f: 220.5
data.str: Hello

Note: Each assignment overwrites the previous one because all members share the
same memory.

2. Difference Table — Output not needed (it's a reference table).

Enumerations in C

1. Defining Enums Using enum Keyword


Color code: 1
2. Accessing Enum Values
Weekend is near!
3. Custom Starting Values
Level value: 20
🧠 Structure Padding vs Packing in C

Structure Padding

Padding is extra bytes the compiler adds between members to align them for faster
access (depending on CPU architecture).

#include <stdio.h>

struct Padded {
char a; // 1 byte
// 3 bytes padding
int b; // 4 bytes
};

int main() {
printf("Size of struct Padded: %lu\n",
sizeof(struct Padded)); // Output: 8 on most 32-bit or
64-bit systems
return 0;
}

Why? After char a, 3 empty bytes are added to align int b to a 4-byte
boundary.
Structure Packing

Packing avoids padding to save memory. It uses #pragma pack(1).

#include <stdio.h>
#pragma pack(1)

struct Packed {
char a; // 1 byte
int b; // 4 bytes
};

int main() {
printf("Size of struct Packed: %lu\n",
sizeof(struct Packed)); // Output: 5
return 0;
}

Note: Accessing packed members can be slower due to misalignment.

Padding vs Packing: Summary Table

Feature Padding Packing

Memory Usage More (due to gaps) Less

Speed Faster access Slower access


Feature Padding Packing

Compiler Default behavior Requires pragma/directive

Use Case Performance optimized Memory-constrained systems

📦 Memory Allocation Examples

1. Structure Size Calculation

struct Example {
char a; // 1 byte
// 3 bytes padding
int b; // 4 bytes
char c; // 1 byte
// 3 bytes padding
};

Total size = 12 bytes (on 4-byte alignment)

2. Union Memory Calculation

union U {
int a; // 4 bytes
float b; // 4 bytes
char str[10]; // 10 bytes
};
int main() {
printf("Size of union: %lu\n", sizeof(union U)); //
Output: 10
return 0;
}

Memory is shared, so size = largest member → str[10]

3. Nested Structure Memory

struct Inner {
int x;
char y;
};

struct Outer {
char z;
struct Inner i;
};

int main() {
printf("Size: %lu\n", sizeof(struct Outer)); //
Padding depends on platform
return 0;
}
🔁 Struct Inside Union
union Mixed {
int i;
struct {
char c;
float f;
} s;
};

int main() {
union Mixed m;
m.s.c = 'X';
m.s.f = 1.5;
printf("Char: %c, Float: %.2f\n", m.s.c, m.s.f);
return 0;
}

Total union size = size of the largest member (struct inside here)

🔁 Union Inside Struct


struct Holder {
char type;
union {
int i;
float f;
} value;
};

int main() {
struct Holder h;
h.type = 'i';
h.value.i = 100;
printf("Value: %d\n", h.value.i);
return 0;
}

💡 Practical Use Cases

Concept Use Case Example

Struct Grouping fields like name, age, marks

Union Same memory space used for different purposes

Enum Readable constant sets like Days, Levels

📚 BONUS: Full Example With Everything Combined


#include <stdio.h>
#include <string.h>
#pragma pack(1)

enum Gender {MALE, FEMALE, OTHER};


struct Date {
int day, month, year;
};

union ID {
int aadhaar;
char passport[10];
};

struct Person {
char name[50];
enum Gender gender;
struct Date dob;
union ID id;
};

int main() {
struct Person p;
strcpy(p.name, "Alice");
p.gender = FEMALE;
p.dob.day = 5;
p.dob.month = 3;
p.dob.year = 2000;
p.id.aadhaar = 123456789;

printf("Name: %s\n", p.name);


printf("Gender: %d\n", p.gender); // 1 for FEMALE
printf("DOB: %02d-%02d-%04d\n", p.dob.day,
p.dob.month, p.dob.year);
printf("Aadhaar: %d\n", p.id.aadhaar);

printf("Total Size of Person: %lu bytes\n",


sizeof(struct Person));
return 0;
}

You might also like