我正在尝试更多地了解 C 及其神秘的隐藏功能,并尝试制作一个包含指向 void 的指针的示例结构,旨在用作数组。编辑:重要提示:这是针对原始 C 代码的。
假设我有这个结构。
typedef struct mystruct {
unsigned char foo;
unsigned int max;
enum data_t type;
void* data;
} mystruct;
我希望数据保存无符号字符、无符号短整数和无符号长整数的最大值,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