#help me create a better array

11 messages · Page 1 of 1 (latest)

fringe jackal
#
#include<stdio.h>
#include<stdlib.h>
#include<stdarg.h>

typedef void* array;

typedef struct
{
    size_t size;
    int data[]; 
} array_header;

array_header* array_get_header(array arr) { return &((array_header*)arr)[-1]; }
size_t len(array arr) { return array_get_header(arr)->size; }

array array_create(size_t count, ...) {
    size_t total_size = sizeof(array_header) + count * sizeof(int);
    
    array_header* h = (array_header*)malloc(total_size);
    if (!h) return NULL;
    
    h->size = count;
    
    va_list args;
    va_start(args, count);
    for (size_t i = 0; i < count; i++) {
        h->data[i] = va_arg(args, int);
    }
    va_end(args);
    
    return &h->data;
}

#define ARRAY_CREATE(...) array_create(sizeof((int[]){__VA_ARGS__}) / sizeof(int), __VA_ARGS__)
int main(void) {
    int* arr =  ARRAY_CREATE(1,2,3);
    printf("%d\n", arr[1]);
    printf("%d\n", len(arr));

    return 0;
}

i couldn't figure out how to make it more generic (for example how to make i can also hold other types with same macro, like):

char* arr =  ARRAY_CREATE('a','b','c');
printf("%c", arr[1]);
float* arr =  ARRAY_CREATE(1.1,2.2,3.3);
printf("%f", arr[1]);
topaz crystalBOT
#

When your question is answered use !solved to mark the question as resolved.

Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For tips on how to ask a good question use !howto ask.

fringe jackal
#

also i'm doing this cuz i want to have arrays with length cuz im tired of having to pass length of an array each time

pastel tapir
#

Your wants describe C++.

fringe jackal
#

an opinion would be appreciated

fringe jackal
#

!solved

topaz crystalBOT
#

Thank you and let us know if you have any more questions!

This thread is now set to auto-hide after an hour of inactivity

strong wyvern
#

The code you pasted in the intro post has some problems.

fringe jackal