C Structures - Arrays, Pointers, and User-Defined Types

This page delves into more complex data structures and memory management in C. It covers arrays, strings, pointers, and user-defined types like structs, unions, and enums, along with their practical examples.

1. Arrays

A collection of elements of the same data type, stored in contiguous memory locations. Elements are accessed using an index (starting from 0).

Code Example (Arrays)

Copied!
#include <stdio.h>

int main() {
    // One-dimensional array
    int numbers[5] = {10, 20, 30, 40, 50};
    printf("Elements of numbers array: ");
    for (int i = 0; i < 5; i++) {
        printf("%d ", numbers[i]);
    }
    printf("\n");

    // Accessing an element
    printf("Third element of numbers: %d\n", numbers[2]);

    // Modifying an element
    numbers[0] = 5;
    printf("First element after modification: %d\n", numbers[0]);

    // Two-dimensional array (matrix)
    int matrix[2][3] = {{1, 2, 3}, {4, 5, 6}};
    printf("Elements of matrix:\n");
    for (int i = 0; i < 2; i++) {
        for (int j = 0; j < 3; j++) {
            printf("%d ", matrix[i][j]);
        }
        printf("\n");
    }

    return 0;
}
            

Expected Output

Elements of numbers array: 10 20 30 40 50
Third element of numbers: 30
First element after modification: 5
Elements of matrix:
1 2 3
4 5 6
            

2. Strings

In C, strings are essentially character arrays terminated by a null character (\0). Many standard library functions operate on null-terminated strings.

Code Example (Strings)

Copied!
#include <stdio.h>
#include <string.h> // For strlen, strcpy, strcat, strcmp

int main() {
    char greeting[10] = "Hello"; // String literal, size is 6 (5 chars + null terminator)
    char name[] = "World";      // Size automatically determined, includes null terminator
    char combined[20];

    printf("Greeting: %s\n", greeting);
    printf("Length of greeting: %zu\n", strlen(greeting)); // %zu for size_t

    strcpy(combined, greeting); // Copy greeting to combined
    strcat(combined, " ");      // Concatenate a space
    strcat(combined, name);     // Concatenate name
    printf("Combined string: %s\n", combined);

    if (strcmp(greeting, "Hello") == 0) { // Compare strings
        printf("Greeting is 'Hello'\n");
    }

    return 0;
}
            

Expected Output

Greeting: Hello
Length of greeting: 5
Combined string: Hello World
Greeting is 'Hello'
            

3. Pointers

A variable that stores the memory address of another variable. Pointers are fundamental for direct memory manipulation, dynamic memory allocation, and efficient array/string handling.

Code Example (Pointers)

Copied!
#include <stdio.h>

void say_hello() {
    printf("Hello from a function pointer!\n");
}

int add(int a, int b) {
    return a + b;
}

int main() {
    int value = 10;
    int *ptr_value; // Declare a pointer to an int

    ptr_value = &value; // Store the address of 'value' in 'ptr_value'

    printf("Value: %d\n", value);
    printf("Address of value: %p\n", (void*)&value); // %p for pointer address
    printf("Value of ptr_value (address it holds): %p\n", (void*)ptr_value);
    printf("Value pointed to by ptr_value: %d\n", *ptr_value); // Dereference

    *ptr_value = 20; // Change value through pointer
    printf("Value after changing via pointer: %d\n", value);

    // Pointer to pointer
    int **pp_value = &ptr_value;
    printf("Value pointed to by pp_value: %d\n", **pp_value);

    // Function pointer
    void (*func_ptr)(); // Declare a function pointer that takes no args and returns void
    func_ptr = say_hello; // Assign the address of the function
    func_ptr(); // Call the function through the pointer

    int (*math_op)(int, int); // Function pointer for int(int, int)
    math_op = add;
    printf("Result of add via function pointer: %d\n", math_op(5, 3));

    return 0;
}
            

Expected Output

Value: 10
Address of value: 0x7ffee1234567 (actual address will vary)
Value of ptr_value (address it holds): 0x7ffee1234567 (actual address will vary)
Value pointed to by ptr_value: 10
Value after changing via pointer: 20
Value pointed to by pp_value: 20
Hello from a function pointer!
Result of add via function pointer: 8
            

4. User-Defined Data Types (Structs, Unions, Enums, Typedef)

Ways to create custom data types to organize related data.

Code Example (User-Defined Types)

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

// Structure definition
struct Person {
    char name[50];
    int age;
    float height;
};

// Union definition
union Data {
    int i;
    float f;
    char str[20];
};

// Enum definition
enum Day {
    SUNDAY = 1, // Assigning explicit value
    MONDAY,     // Automatically 2
    TUESDAY,
    WEDNESDAY,
    THURSDAY,
    FRIDAY,
    SATURDAY
};

// Typedef example
typedef struct Point {
    int x;
    int y;
} Point2D; // New name for struct Point

int main() {
    // Struct example
    struct Person person1;
    strcpy(person1.name, "Alice");
    person1.age = 25;
    person1.height = 1.65;

    printf("Person 1: Name: %s, Age: %d, Height: %.2f\n", person1.name, person1.age, person1.height);

    // Union example
    union Data data;
    data.i = 10;
    printf("Union (int): %d\n", data.i);
    data.f = 22.5; // Overwrites the integer value
    printf("Union (float): %.1f\n", data.f);
    strcpy(data.str, "C Programming"); // Overwrites float value
    printf("Union (string): %s\n", data.str);
    // printf("Union (int after string): %d\n", data.i); // Will print garbage

    // Enum example
    enum Day today = WEDNESDAY;
    printf("Today is day number: %d\n", today);

    if (today == WEDNESDAY) {
        printf("It's Wednesday!\n");
    }

    // Typedef example
    Point2D p1;
    p1.x = 5;
    p1.y = 10;
    printf("Point p1: (%d, %d)\n", p1.x, p1.y);

    return 0;
}
            

Expected Output

Person 1: Name: Alice, Age: 25, Height: 1.65
Union (int): 10
Union (float): 22.5
Union (string): C Programming
Today is day number: 4
It's Wednesday!
Point p1: (5, 10)