CData TypesDerived Data Type

Derived Data Types in C

Overview

Derived data types in C are built from the basic data types and allow for more complex data structures. They enable programmers to manage collections of data efficiently and create custom data structures tailored to specific needs. The main derived data types in C include arrays, structures, unions, and pointers.

1. Arrays

An array is a collection of variables of the same type stored in contiguous memory locations. Arrays allow you to store multiple values in a single variable, making it easier to manage large amounts of data.

Example: Array

array.c
#include <stdio.h>
 
int main() {
    int numbers[5] = {1, 2, 3, 4, 5}; // Declaration and initialization of an array
    printf("First number: %d\n", numbers[0]); // Output: First number: 1
    return 0;
}

2. Structures

A structure is a user-defined data type that allows grouping of different data types. Structures are useful for representing complex entities with multiple attributes.

Example: Structure

structure.c
#include <stdio.h>
 
struct Person {
    char name[50];
    int age;
};
 
int main() {
    struct Person person = {"Alice", 30}; // Declaration and initialization of a structure
    printf("Name: %s, Age: %d\n", person.name, person.age); // Output: Name: Alice, Age: 30
    return 0;
}

3. Unions

A union is similar to a structure but can store different data types in the same memory location. All members of a union share the same memory space, which means only one member can hold a value at any given time.

Example: Union

union.c
#include <stdio.h>
 
union Data {
    int intValue;
    float floatValue;
};
 
int main() {
    union Data data; // Declaration of a union
    data.intValue = 10; // Assigning an integer value
    printf("Integer: %d\n", data.intValue); // Output: Integer: 10
    data.floatValue = 5.5; // Assigning a float value
    printf("Float: %.1f\n", data.floatValue); // Output: Float: 5.5
    return 0;
}

4. Pointers

A pointer is a variable that stores the address of another variable. Pointers are powerful tools in C that allow for dynamic memory management and efficient data manipulation.

Example: Pointer

pointer.c
#include <stdio.h>
 
int main() {
    int value = 42; // Declaration of an integer variable
    int *ptr = &value; // Declaration of a pointer variable
    printf("Value: %d, Address: %p\n", *ptr, (void*)ptr); // Output: Value: 42, Address: <address>
    return 0;
}

Conclusion

Derived data types in C provide the flexibility and complexity needed to manage and manipulate data efficiently. Arrays allow for the storage of multiple values, structures enable the grouping of different data types, unions provide shared memory space for different data types, and pointers offer powerful memory management capabilities. Understanding these derived data types is essential for writing effective and efficient C programs.