C dynamically growing array

前端 未结 7 2013
闹比i
闹比i 2020-11-22 07:57

I have a program that reads a \"raw\" list of in-game entities, and I intend to make an array holding an index number (int) of an indeterminate number of entities, for proce

7条回答
  •  醉酒成梦
    2020-11-22 08:27

    To create an array of unlimited items of any sort of type:

    typedef struct STRUCT_SS_VECTOR {
        size_t size;
        void** items;
    } ss_vector;
    
    
    ss_vector* ss_init_vector(size_t item_size) {
        ss_vector* vector;
        vector = malloc(sizeof(ss_vector));
        vector->size = 0;
        vector->items = calloc(0, item_size);
    
        return vector;
    }
    
    void ss_vector_append(ss_vector* vec, void* item) {
        vec->size++;
        vec->items = realloc(vec->items, vec->size * sizeof(item));
        vec->items[vec->size - 1] = item;
    };
    
    void ss_vector_free(ss_vector* vec) {
        for (int i = 0; i < vec->size; i++)
            free(vec->items[i]);
    
        free(vec->items);
        free(vec);
    }
    

    and how to use it:

    // defining some sort of struct, can be anything really
    typedef struct APPLE_STRUCT {
        int id;
    } apple;
    
    apple* init_apple(int id) {
        apple* a;
        a = malloc(sizeof(apple));
        a-> id = id;
        return a;
    };
    
    
    int main(int argc, char* argv[]) {
        ss_vector* vector = ss_init_vector(sizeof(apple));
    
        // inserting some items
        for (int i = 0; i < 10; i++)
            ss_vector_append(vector, init_apple(i));
    
    
        // dont forget to free it
        ss_vector_free(vector);
    
        return 0;
    }
    

    This vector/array can hold any type of item and it is completely dynamic in size.

提交回复
热议问题