Structure in c
A structure in C is a user-defined data type that groups related variables of different data types under a single name. Each member of a structure has its own memory location.
Syntax of Structure in c
struct Student {
int id;
char name[50];
float marks;
};
- Each member is allocated memory separately.
- Accessed using the dot (
.
) operator.
Example of structure in c
#include <stdio.h>
struct Student {
int id;
char name[50];
float marks;
};
int main() {
struct Student s1 = {101, "Alice", 85.5};
printf("ID: %d\n", s1.id);
printf("Name: %s\n", s1.name);
printf("Marks: %.2f\n", s1.marks);
return 0;
}
Union in c
A union is a user-defined data type similar to a structure, but in a union, all members share the same memory location. The size of the union is equal to the size of the largest member.
Syntax of Union in c
union Data {
int id;
char name[50];
float marks;
};
- Only one member can hold a value at a time.
- Accessed using the dot (
.
) operator.
Example of union in c
#include <stdio.h>
union Data {
int id;
char name[50];
float marks;
};
int main() {
union Data d1;
d1.id = 101;
printf("ID: %d\n", d1.id);
d1.marks = 85.5; // Overwrites 'id' value
printf("Marks: %.2f\n", d1.marks);
return 0;
}
Difference Between Structure and Union
Feature | Structure | Union |
---|---|---|
Memory | Each member has its own memory. | All members share the same memory. |
Size | Sum of all members’ sizes. | Size of the largest member. |
Storage | Stores multiple values at a time. | Stores only one value at a time. |
Access | All members can be accessed independently. | Only the last assigned member holds a valid value. |
Use Case | Used when all members need to hold values. | Used when only one value is needed at a time to save memory. |
Pointer in Structure in C
A pointer to a structure is a pointer that holds the address of a structure variable. This allows efficient manipulation of structure data.
Declaring a Pointer to a Structure
struct Student {
int id;
char name[50];
float marks;
};
struct Student *ptr; // Pointer to a structure
Accessing Structure Members Using Pointer
Since a structure pointer holds the address of a structure, we use the ->
(arrow operator) to access its members.
Example
#include <stdio.h>
struct Student {
int id;
char name[50];
float marks;
};
int main() {
struct Student s1 = {101, "Alice", 85.5}; // Structure variable
struct Student *ptr = &s1; // Pointer to structure
// Accessing members using pointer
printf("ID: %d\n", ptr->id);
printf("Name: %s\n", ptr->name);
printf("Marks: %.2f\n", ptr->marks);
return 0;
}
Output:
ID: 101
Name: Alice
Marks: 85.50
Instead of ptr->id
, we can also use (*ptr).id
, but ->
is preferred.
Dynamic Memory Allocation for Structure Pointer
You can dynamically allocate memory to a structure using malloc()
.
Example
#include <stdio.h>
#include <stdlib.h>
struct Student {
int id;
char name[50];
float marks;
};
int main() {
struct Student *ptr;
ptr = (struct Student *)malloc(sizeof(struct Student)); // Memory allocation
if (ptr == NULL) {
printf("Memory allocation failed\n");
return 1;
}
// Assign values
ptr->id = 102;
strcpy(ptr->name, "Bob");
ptr->marks = 90.2;
// Print values
printf("ID: %d\n", ptr->id);
printf("Name: %s\n", ptr->name);
printf("Marks: %.2f\n", ptr->marks);
free(ptr); // Free allocated memory
return 0;
}
Array of Structure Pointers
We can create an array of pointers to structures for handling multiple records.
Example
#include <stdio.h>
struct Student {
int id;
char name[50];
float marks;
};
int main() {
struct Student s1 = {101, "Alice", 85.5};
struct Student s2 = {102, "Bob", 90.2};
struct Student *arr[] = {&s1, &s2}; // Array of structure pointers
for (int i = 0; i < 2; i++) {
printf("ID: %d, Name: %s, Marks: %.2f\n", arr[i]->id, arr[i]->name, arr[i]->marks);
}
return 0;
}
Structure Pointer Inside Another Structure
A structure can have a pointer to another structure.
Example
#include <stdio.h>
struct Address {
char city[50];
int pin;
};
struct Student {
int id;
struct Address *addr; // Pointer to Address structure
};
int main() {
struct Address addr1 = {"New York", 12345};
struct Student s1 = {101, &addr1}; // Assign address pointer
printf("Student ID: %d\n", s1.id);
printf("City: %s\n", s1.addr->city);
printf("Pin: %d\n", s1.addr->pin);
return 0;
}
Pointer in Union in C
A pointer to a union is similar to a pointer to a structure, but since a union shares memory among its members, only one member can hold a valid value at a time.
Declaring a Pointer to a Union
union Data {
int id;
float marks;
char name[50];
};
union Data *ptr; // Pointer to a union
Accessing Union Members Using Pointer
Since a union pointer holds the address of a union variable, we use the ->
(arrow operator) to access its members.
Example
#include <stdio.h>
union Data {
int id;
float marks;
char name[50];
};
int main() {
union Data d1; // Union variable
union Data *ptr = &d1; // Pointer to union
ptr->id = 101;
printf("ID: %d\n", ptr->id);
ptr->marks = 85.5; // Overwrites id
printf("Marks: %.2f\n", ptr->marks);
return 0;
}
Output:
ID: 101
Marks: 85.50
Notice that the id
value is lost when we assign marks
, as they share the same memory.
Dynamic Memory Allocation for Union Pointer
We can allocate memory dynamically to a union pointer using malloc()
.
Example
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
union Data {
int id;
float marks;
char name[50];
};
int main() {
union Data *ptr;
ptr = (union Data *)malloc(sizeof(union Data)); // Memory allocation
if (ptr == NULL) {
printf("Memory allocation failed\n");
return 1;
}
ptr->id = 102;
printf("ID: %d\n", ptr->id);
ptr->marks = 90.2; // Overwrites id
printf("Marks: %.2f\n", ptr->marks);
strcpy(ptr->name, "Bob"); // Overwrites marks
printf("Name: %s\n", ptr->name);
free(ptr); // Free allocated memory
return 0;
}
Array of Union Pointers
We can create an array of pointers to unions to manage multiple data records.
Example
#include <stdio.h>
union Data {
int id;
float marks;
};
int main() {
union Data d1, d2;
union Data *arr[] = {&d1, &d2}; // Array of union pointers
arr[0]->id = 101;
printf("ID: %d\n", arr[0]->id);
arr[1]->marks = 92.5;
printf("Marks: %.2f\n", arr[1]->marks);
return 0;
}
Union Pointer Inside a Structure
A structure can have a pointer to a union.
Example
#include <stdio.h>
union Data {
int id;
float marks;
};
struct Student {
int roll_no;
union Data *info; // Pointer to a union
};
int main() {
union Data d1;
d1.id = 101;
struct Student s1;
s1.roll_no = 1;
s1.info = &d1; // Assign union pointer to structure
printf("Roll No: %d\n", s1.roll_no);
printf("ID: %d\n", s1.info->id);
return 0;
}
Interview Questions on struct in C
1. Basic Questions
- What is a
struct
in C? - How does a
struct
differ from a normal variable? - Can a structure contain different data types?
- How do you define and declare a structure in C?
- What is the difference between
struct
andunion
? - How can we initialize a structure in C?
- How do you access structure members?
- What is the size of an empty structure in C?
- Can a structure have an array as a member?
- Can we declare a structure without defining its members?
2. Advanced Questions
- What happens when you assign one structure variable to another?
- Can you compare two structures using
==
operator? Why or why not? - How can you pass a structure to a function?
- What is the difference between passing a structure by value and by reference?
- How do you return a structure from a function?
- Can a structure contain a pointer to itself? Explain with an example.
- What is a self-referential structure? Where is it used?
- Can a structure be nested inside another structure? Provide an example.
- How is memory allocated for structures in C?
- How can we reduce structure padding in C?
3. Struct with Pointers
- How do you declare a pointer to a structure?
- What is the difference between
ptr->member
and(*ptr).member
? - How do you dynamically allocate memory for a structure using
malloc()
? - Can a structure contain a pointer to another structure? Explain.
- How do you create an array of structure pointers?
- How do you free dynamically allocated structures?
4. Typedef and Struct
- What is the use of
typedef
with structures? - What is the difference between
typedef struct
andstruct
? - How do you define an alias for a structure using
typedef
? - What are the advantages of using
typedef
with structures?
5. Struct in Real-Time Scenarios
- How are structures used in embedded systems?
- How are structures useful in writing device drivers?
- How do structures help in creating linked lists and trees?
- Can we create an array of structures? Provide an example.
- How are structures stored in memory, and how does alignment affect them?
- What is structure packing, and how is it done in C?
- What is the use of
#pragma pack(1)
in structures? - How does endianness affect structure storage?
- How are structures used for network packet handling?
- How do we write a structure to a file using
fwrite()
?
6. Struct vs Other Data Types
- What is the difference between a
struct
and aclass
in C++? - How is
struct
different fromenum
? - Can we have function pointers inside a structure?
- Can a structure be defined inside a function? What are the implications?
- Can a structure be declared as
const
? - Can a structure be volatile? What does it mean?
7. Miscellaneous
- Can you store a structure in a union?
- Can we have an anonymous structure in C?
- How do you create a structure with flexible array members?
- What is the use of
offsetof()
macro in C?
Interview Questions on union
in C
Here is a comprehensive list of union-related interview questions categorized by difficulty level:
1. Basic Questions
- What is a
union
in C? - How does a
union
differ from astruct
? - What is the syntax of defining and using a
union
in C? - How is memory allocated for a
union
? - What is the size of a
union
? - Can a
union
store multiple values at the same time? - How do you initialize a
union
in C? - How do you access union members?
- What happens when you assign a value to one member of a
union
? - Can we compare two union variables using
==
?
2. Advanced Questions
- What is the difference between
typedef struct
andtypedef union
? - Can a
union
contain a pointer to itself? - How do you pass a
union
to a function? - How do you return a
union
from a function? - What happens if a union has members of different data types and we access the wrong member?
- What is type punning in
union
? - How can a
union
be used for endianness conversion? - What happens if we use
sizeof()
on aunion
? - How does
union
help in saving memory in embedded systems? - Can a
union
contain an array?
3. Union with Pointers
- How do you declare a pointer to a
union
? - What is the difference between
ptr->member
and(*ptr).member
in unions? - How do you dynamically allocate memory for a
union
? - Can a
union
contain a pointer as one of its members? - How do you create an array of union pointers?
4. Union with Structures
- Can a
union
be inside astruct
? Provide an example. - Can a
struct
be inside aunion
? What are the implications? - What is the use case of anonymous unions inside a structure?
- How do you access a union member inside a structure?
- How do you manage alignment and padding in structures containing unions?
5. Real-World Use Cases of Union
- How are unions used in embedded systems?
- How does a
union
help in bit-field manipulation? - How are
union
s used in device drivers? - Why are unions useful for memory-mapped registers?
- How does a
union
help in interpreting raw data formats?
6. Best Practices and Miscellaneous
- What are the advantages and disadvantages of using a
union
? - When should you use a
union
instead of astruct
? - Can a
union
bevolatile
? When is it useful? - What are the risks of using a
union
with multiple data types? - Can we use
union
inside aunion
?
FAQ: Structures and Unions in C – Types, Usage, and Examples
Frequently Asked Questions (FAQ) on Structures in C
1. What is a struct
in C?
A struct
(structure) in C is a user-defined data type that groups variables of different types under a single name.
Example:
struct Student {
int id;
char name[50];
float marks;
};
2. What is typedef struct
and why is it used?
typedef struct
allows you to define a structure with a shorthand alias, improving code readability.
Example:
typedef struct {
int id;
char name[50];
} Student;
Now, Student
can be used instead of struct Student
.
3. What is a Nested Structure in C?
A nested structure is a structure inside another structure.
Example:
struct Address {
char city[50];
int pin;
};
struct Student {
int id;
struct Address addr; // Nested struct
};
4. What is a Bit Field Structure in C?
A bit field structure allows memory-efficient storage of data using specific bit widths.
Example:
struct Status {
unsigned int ready : 1;
unsigned int error : 1;
unsigned int processing : 2;
};
5. What is a Self-Referential Structure in C?
A self-referential structure is a structure that contains a pointer to itself, commonly used in linked lists.
Example:
struct Node {
int data;
struct Node *next; // Self-reference
};
6. What is an Anonymous Structure in C?
An anonymous structure is a structure without a name, usually defined within another structure or union.
Example:
struct {
int id;
char name[50];
} student;
7. What is a Flexible Array Member in a Structure?
A flexible array member is an array with an unspecified size at the end of a structure.
Example:
struct Data {
int length;
char buffer[]; // Flexible array member
};
8. What is a Packed Structure in C?
A packed structure reduces padding and optimizes memory usage by forcing strict alignment.
Example:
#pragma pack(1)
struct PackedData {
char a;
int b;
};
9. What is a Structure with Function Pointers?
A structure can contain function pointers to store and invoke functions dynamically.
Example:
struct Operation {
int (*add)(int, int);
};
10. How are Structures Used in Linked Lists and Trees?
Structures help in data representation for linked lists and trees using self-referential pointers.
Example (Linked List Node):
struct Node {
int data;
struct Node* next;
};
Frequently Asked Questions (FAQ) on Unions in C
1. What is a union
in C?
A union
is a user-defined data type where all members share the same memory location, making it memory-efficient.
Example:
union Data {
int id;
float marks;
};
2. What is typedef union
and why is it used?
typedef union
creates a union alias for easier use.
Example:
typedef union {
int id;
float marks;
} Data;
3. What is an Anonymous Union in C?
An anonymous union is a union without a name, directly embedded within a structure.
Example:
struct {
union {
int id;
float marks;
};
} student;
4. What is a Self-Referential Union in C?
A self-referential union contains a pointer to itself, similar to a self-referential structure.
Example:
union Node {
int data;
union Node *next;
};
5. What is a Bit Field Union in C?
A bit field union allows memory-efficient representation using bit fields.
Example:
union Status {
struct {
unsigned int ready : 1;
unsigned int error : 1;
unsigned int processing : 2;
};
int full_status;
};
6. How is a Union Used Inside a Structure?
A union can be embedded in a structure to allow flexible data representation.
Example:
struct Employee {
int empID;
union {
int salary;
float hourly_rate;
} pay;
};
7. What Happens When a Union Contains Different Data Types?
Only one member can hold valid data at a time, so assigning one member will overwrite others.
Example:
union Data {
int id;
float marks;
};
union Data d;
d.id = 100;
printf("%d", d.id);
d.marks = 85.5;
printf("%f", d.marks); // Overwrites previous data
8. How are Unions Used in Device Drivers?
Unions help in accessing hardware registers and memory-mapped I/O efficiently.
Example:
union Register {
struct {
unsigned int enable : 1;
unsigned int mode : 2;
unsigned int reserved : 5;
};
unsigned char reg_value;
};
9. How Does a Union Optimize Memory Usage?
Since all union members share the same memory, it reduces memory consumption compared to structures.
10. What is Type Punning Using Unions?
Type punning allows interpreting a memory region as different data types.
Example:
union Convert {
int i;
float f;
};
union Convert c;
c.i = 1065353216; // Binary representation of 1.0 in IEEE 754
printf("%f", c.f); // Prints 1.0
Conclusion: Understanding Structures and Unions in C
Structures and unions are fundamental building blocks in C programming, enabling efficient data organization and memory management.
- Structures (
struct
) allow grouping multiple variables of different data types, making them ideal for defining complex data models like linked lists, trees, and configuration settings. They offer data encapsulation, structured representation, and ease of access. - Unions (
union
) provide a memory-efficient alternative where multiple variables share the same memory location. They are particularly useful in scenarios where only one variable is needed at a time, such as device drivers, low-level memory handling, and hardware register manipulation.
Key Takeaways
✅ Use structures when you need to store and access multiple fields independently.
✅ Use unions when memory optimization is critical, and only one field needs to be accessed at a time.
✅ Both structures and unions support pointers, typedef, nesting, bit fields, and function pointers, making them versatile tools for embedded systems, networking, and system programming.
✅ Understanding how to leverage these data types efficiently can lead to optimized memory usage, better performance, and scalable software design.
Mastering structures and unions will significantly enhance your C programming skills, especially if you work in embedded systems, low-level programming, or high-performance applications. Keep exploring, experimenting, and optimizing!
Structures and unions in C are user-defined data types that allow grouping of variables. Structures group variables of different data types under a single name, with each member having its own memory location. Unions, on the other hand, allow storing different data types in the same memory location, with the size of the union being equal to its largest member. citeturn0search0
Frequently Asked Questions (FAQ) on Structures and Unions in C
1. What is a structure in C? A structure in C is a user-defined data type that groups related variables of different data types under a single name. Each member of a structure has its own memory location. citeturn0search0
2. How do you define a structure in C? A structure is defined using the struct
keyword, followed by the structure name and a block containing the member declarations. For example:
struct Student {
int id;
char name[50];
float marks;
};
3. How do you access members of a structure? Members of a structure are accessed using the dot (.
) operator with the structure variable. For example:
struct Student s1;
s1.id = 101;
4. What is a union in C? A union in C is a user-defined data type similar to a structure, but in a union, all members share the same memory location. This means only one member can hold a value at any given time.
5. How do you define a union in C? A union is defined using the union
keyword, followed by the union name and a block containing the member declarations. For example:
union Data {
int id;
char name[50];
float marks;
};
6. How do you access members of a union? Members of a union are accessed using the dot (.
) operator with the union variable. For example:
union Data d1;
d1.id = 101;
7. What is the main difference between structures and unions? The main difference is in memory allocation. In structures, each member has its own memory location, allowing multiple members to hold values simultaneously. In unions, all members share the same memory location, so only one member can hold a value at a time. citeturn0search0
8. How do you declare a pointer to a structure? A pointer to a structure is declared by specifying the structure type followed by an asterisk (*
) and the pointer name. For example:
struct Student *ptr;
9. How do you access structure members using a pointer? When using a pointer to a structure, members are accessed using the arrow (->
) operator. For example:
struct Student s1;
struct Student *ptr = &s1;
ptr->id = 101;
10. How do you dynamically allocate memory for a structure pointer? Dynamic memory allocation for a structure pointer is done using the malloc
function. For example:
struct Student *ptr = (struct Student *)malloc(sizeof(struct Student));
11. Can structures contain pointers to themselves? Yes, structures can contain pointers to themselves, enabling the creation of complex data structures like linked lists. For example:
struct Node {
int data;
struct Node *next;
};
12. Can unions be nested within structures? Yes, unions can be nested within structures to create flexible data structures. For example:
struct Container {
int type;
union {
int intValue;
float floatValue;
char *stringValue;
} data;
};
13. What are bit fields in structures? Bit fields allow the allocation of a specific number of bits to structure members, enabling memory-efficient storage of data requiring limited bit-width. For example:
struct {
unsigned int flag : 1;
unsigned int value : 4;
} bitField;
14. How do you initialize structures and unions? Structures and unions can be initialized at the time of declaration. For structures:
struct Student s1 = {101, "Alice", 85.5};
For unions:
union Data d1 = {101};
15. What are anonymous unions? Anonymous unions are unions without a name, allowing their members to be accessed directly without a union variable. They are typically used within structures. For example:
struct Example {
int type;
union {
int intValue;
float floatValue;
};
};
16. What are the use cases for structures and unions? Structures are used when multiple related variables of different types need to be grouped together, each holding its own value. Unions are used when a variable may hold different types of data at different times, conserving memory by sharing the same memory location.
Thank you for exploring this tutorial! Stay ahead in embedded systems with expert insights, hands-on projects, and in-depth guides. Follow Embedded Prep for the latest trends, best practices, and step-by-step tutorials to enhance your expertise. Keep learning, keep innovating!
Pingback: Top 30+ I2C Interview Questions & Answers (Basic to Advanced) – Embedded Prep
Pingback: What is eMMC (Embedded MultiMediaCard) memory ? – Embedded Prep
Pingback: Multithreading Interview Question – Embedded Prep
Pingback: LED Blinking with Arduino – Embedded Prep
Pingback: Storage Classes in C interview questions – Embedded Prep
Pingback: ALSA interview questions – Embedded Prep