Derived Data Types in C Language
Introduction
In C programming, derived data types are those that are derived from the fundamental data types. These types provide advanced features and capabilities for handling complex data structures. The main derived data types in C are arrays, pointers, structures, and unions.
1. Arrays
An array is a collection of elements of the same data type stored in contiguous memory locations. Arrays are used to store multiple values in a single variable, instead of declaring separate variables for each value.
Example of an array declaration and initialization:
Accessing array elements:
2. Pointers
Pointers are variables that store the address of another variable. They are powerful features in C that allow for dynamic memory allocation, efficient array handling, and the creation of complex data structures like linked lists and trees.
Example of a pointer declaration and initialization:
int *p = &a;
Accessing the value using a pointer:
3. Structures
Structures (structs) are user-defined data types that allow the combination of data items of different kinds. They are used to group related variables under one name for easier handling and management.
Example of a structure declaration and initialization:
char name[50];
int age;
};
struct Person person1 = {"John Doe", 30};
Accessing structure members:
4. Unions
Unions are similar to structures, but they differ in the way memory is allocated. In a union, all members share the same memory location, which means that only one member can hold a value at any given time. This can save memory when dealing with variables that do not need to store values simultaneously.
Example of a union declaration and initialization:
int i;
float f;
char str[20];
};
union Data data;
data.i = 10;
Accessing union members:
Conclusion
Derived data types in C provide flexibility and efficiency in handling various kinds of data structures. Understanding and using these data types effectively can lead to more powerful and optimized programs. Arrays, pointers, structures, and unions each have their unique characteristics and use cases, making them integral parts of the C programming language.