【发布时间】:2011-10-20 07:28:09
【问题描述】:
我正在尝试更多地了解 C 及其神秘的隐藏功能,并且我尝试制作一个包含指向 void 的指针的示例结构,旨在用作数组。 编辑:重要提示:这是针对原始 C 代码的。
假设我有这个结构。
typedef struct mystruct {
unsigned char foo;
unsigned int max;
enum data_t type;
void* data;
} mystruct;
我希望数据保存 max 无符号字符、无符号短整数和无符号长整数,data_t 枚举包含 这 3 种情况的值。
enum Grid_t {gi8, gi16, gi32}; //For 8, 16 and 32 bit uints.
然后我有这个函数来初始化和分配其中一个结构,并且应该返回一个指向新结构的指针。
mystruct* new(unsigned char foo, unsigned int bar, long value) {
mystruct* new;
new = malloc(sizeof(mystruct)); //Allocate space for the struct.
assert(new != NULL);
new->foo = foo;
new->max = bar;
int i;
switch(type){
case gi8: default:
new->data = (unsigned char *)calloc(new->max, sizeof(unsigned char));
assert(new->data != NULL);
for(i = 0; i < new->max; i++){
*((unsigned char*)new->data + i) = (unsigned char)value;
//Can I do anything with the format new->data[n]? I can't seem
//to use the [] shortcut to point to members in this case!
}
break;
}
return new;
}
编译器不返回任何警告,但我不太确定这种方法。使用指针是否合法?
有没有更好的方法©?
我错过了呼叫它。像 mystruct* P; P = 新的(0,50,1024);
工会很有趣,但不是我想要的。由于无论如何我都必须单独处理每个特定案例,因此铸造似乎与工会一样好。我特别希望 8 位数组比 32 位数组大得多,所以联合似乎没有帮助。为此,我将其设为 long 数组:P
【问题讨论】:
-
要回答 cmets 中的问题,您不能使用 [] 因为取消引用 void 指针是非法的。如果您使用 void 指针,那么您需要在每个取消引用周围都使用该 switch 语句,以便您可以在运行时将指针转换为正确的类型。
-
这实际上是我的意图。
-
您的代码只是 C99,而不是“原始 C”。 “原始C”是C89。您的代码不起作用,在“switch(type)”中“type”未定义。
-
@user4 这是在帖子中做模型时的拼写错误,而不是在实际代码中。而且之前就被发现了。
标签: c arrays pointers void dereference