在 C 中实现泛型向量

问题描述 投票:0回答:0

只需在 c 中实现通用向量结构。

vector_init()
函数初始化
vector_t
结构并根据类型参数设置类型。然而不久之后,在实施
vector_push()
时我意识到我将不得不再次经历同样的事情。

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

#define INTEGER 0
#define CHAR 1
#define STRING 2
#define FLOAT 3
#define DOUBLE 4

typedef struct {
    void*  arr;
    size_t length;
    size_t capacity;
}vector_t;

int vector_init(vector_t *vec,int type, size_t length){
    if(length < 0)
        return -1;
    
    switch (type){
        case 0:
            vec->arr = (int *)malloc(sizeof(int) * length);
            break;
        case 1:
            vec->arr = (char *)malloc(length);
            break;
        case 2:
            vec->arr = (char **)malloc(length);
            break;
        case 3:
            vec->arr = (float *)malloc(sizeof(float) * length);
            break;
        case 4:
            vec->arr = (double *)malloc(sizeof(double) * length);
            break;
        default:
            return -1; 
    };
    vec->length = 0;
    vec->capacity = length;
    
    return 1;
}

我怎样才能让它不那么像初学者?

c vector dynamic malloc
© www.soinside.com 2019 - 2024. All rights reserved.