Use void* to simulate Ruby-like arrays in C

Arrays are typically designed to store elements of the same data type (240610152201), but languages like Ruby allow arrays to store elements of multiple data types (250201111442).

In languages like C, we can simulate this behavior by creating an array of void pointers (void*), which can reference different data types. Each element can then be cast to the appropriate data type when needed.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char **argv) {
    const unsigned SIZE = 4;
    void* arr[SIZE];

    // Store an integer
    arr[0] = malloc(sizeof(int));
    *(int *)arr[0] = 17;

    // Store a float
    arr[1] = malloc(sizeof(float));
    *(float *)arr[1] = 3.14;

    // Store boolean
    arr[2] = malloc(sizeof(int));
    *(int *)arr[2] = 1;

    // Store a string
    arr[3] = malloc(strlen("seventeen") + 1);
    strcpy((char*)arr[3], "seventeen");

    // Print values
    printf("%d\n", *(int *)(arr[0]));
    printf("%.2f\n", *(float *)(arr[1]));
    printf("%s\n", *(int *)(arr[2]) == 1 ? "true" : "false");
    printf("%s\n", (char *)arr[3]);

    // Free allocated memory
    for(int i = 0; i < SIZE; ++i)
        free(arr[i]);

    return 0;
}

Here’s the output.

17
3.14
true
seventeen
Backlinks: