How to dynamically allocate memory for an array and store relevant metadata in struct C

1 Answer

0 votes
#include <stdio.h>
#include <stdlib.h>

// A struct that stores:
// 1. A pointer to a dynamically allocated array
// 2. The number of elements currently used
// 3. The total allocated capacity
typedef struct {
    int *data;        // Pointer to the array in heap memory
    size_t size;      // Number of valid elements
    size_t capacity;  // Total allocated space
} IntArray;


// Initialize the dynamic array with a given starting capacity
void initArray(IntArray *arr, size_t initial_capacity) {

    // Allocate memory for 'initial_capacity' integers
    arr->data = malloc(initial_capacity * sizeof(int));

    // Always check if malloc succeeded
    if (arr->data == NULL) {
        perror("malloc failed");
        exit(EXIT_FAILURE);
    }

    arr->size = 0;                 // No elements yet
    arr->capacity = initial_capacity; // Store allocated capacity
}


// Add a new element to the array, resizing if needed
void pushBack(IntArray *arr, int value) {

    // If array is full, grow it
    if (arr->size == arr->capacity) {

        // Double the capacity for efficiency
        arr->capacity *= 2;

        // Reallocate memory to the new size
        int *newData = realloc(arr->data, arr->capacity * sizeof(int));

        // Check if realloc succeeded
        if (newData == NULL) {
            perror("realloc failed");
            exit(EXIT_FAILURE);
        }

        arr->data = newData; // Update pointer
    }

    // Store the new value and increase size
    arr->data[arr->size] = value;
    arr->size++;
}


// Free the allocated memory and reset metadata
void freeArray(IntArray *arr) {
    free(arr->data);   // Release heap memory
    arr->data = NULL;  // Avoid dangling pointer
    arr->size = 0;
    arr->capacity = 0;
}


int main() {
    IntArray arr;

    // Create array with initial capacity of 6
    initArray(&arr, 6);

    // Add some values
    pushBack(&arr, 7);
    pushBack(&arr, 19);
    pushBack(&arr, 3);
    pushBack(&arr, 87);

    // Print stored values
    for (size_t i = 0; i < arr.size; i++) {
        printf("%d\n", arr.data[i]);
    }

    printf("arr.size = %d\n", arr.size);
    printf("arr.capacity = %d\n", arr.capacity);
    
    // Clean up memory
    freeArray(&arr);

    return 0;
}



/*
run:

7
19
3
87
arr.size = 4
arr.capacity = 6

*/

 



answered May 3 by avibootz

Related questions

2 answers 279 views
1 answer 151 views
151 views asked May 4, 2021 by avibootz
1 answer 214 views
1 answer 183 views
183 views asked Jul 10, 2015 by avibootz
1 answer 223 views
...