为什么我无效使用 void 表达式?

Why do i get invalid use of void expression?

我想在 c 中重新创建向量,但出现无效使用 void 表达式错误。我试过这样。

typedef struct {
    void *data;
    int size;
    int capacity;
} vec;


#define vec_new(name, type) vec name; (name).size = 0; (name).capacity = 8; {\
    void *vec_temp; vec_temp = calloc(8, sizeof(type));\
    while (vec_temp == NULL) { vec_temp = calloc(8, sizeof(type)); }\
    (name).data = vec_temp;\
}


#define vec_set(vec, index, value, type) *( (type*) (vec).data[(index)] ) = value;
#define vec_get(vec, index, type) *( (type*) (vec).data[(index)] )`

我得到了集合中的错误并得到了宏

您正在按原样为 void* 类型编制索引。您正在将 (vec).data[(index)] 类型转换为 type*,您应该将 ((vec).data) 类型转换为 type*

试试这个:

#define vec_set(vec, index, value, type) ((type*) (vec).data)[(index)] = value;
#define vec_get(vec, index, type) (((type*) (vec).data)[(index)])

您对 void 表达式的使用无效,因为我们无法执行 void* 算术和取消引用!您需要转换 data 结构成员,但您做错了。

#include <stdio.h>
#include <stdlib.h>
typedef struct {
    void *data;
    int size;
    int capacity;
} vec;


#define vec_new(name, type) vec name; (name).size = 0; (name).capacity = 8; {\
    void *vec_temp; vec_temp = calloc(8, sizeof(type));\
    while (vec_temp == NULL) { vec_temp = calloc(8, sizeof(type)); }\
    (name).data = vec_temp;\
}



#define vec_set(vec, index, value, type) (*( ( (type*) (vec).data )  + (index) ) ) = value;
#define vec_get(vec, index, type) (*( ( (type*) (vec).data )  + (index) ) )
int main()
{
    
    vec_new(p, int);
    vec_set(p,0,5,int);
    int g = vec_get(p, 0, int);
    
    printf("%d",g);
    return 0;
}