2

我正在尝试更多地了解 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

4

4 回答 4

2

不,您不能取消引用void*指针,这是 C 语言标准所禁止的。在这样做之前,您必须将其转换为具体的指针类型。

作为替代方案,根据您的需要,您还可以union在结构中使用 a 而不是 a void*

typedef struct mystruct {
    unsigned char foo;
    unsigned int max;
    enum data_t type;
    union {
        unsigned char *uc;
        unsigned short *us;
        unsigned int *ui;
    } data;
} mystruct;

在任何给定时间,只有一个data.ucdata.usdata.ui是有效的,因为它们都占用内存中的相同空间。然后,您可以使用适当的成员来获取您的数据数组,而无需从void*.

于 2011-08-04T19:26:25.933 回答
1

关于什么

typedef struct mystruct 
{
    unsigned char foo;
    unsigned int max;
    enum data_t type;
    union
    {
        unsigned char *chars;
        unsigned short *shortints;
        unsigned long *longints; 
    };
} mystruct;

这样一来,就完全不需要投了。只需使用data_t来确定您要访问的指针。

于 2011-08-04T19:24:36.053 回答
0

type应该是函数的参数吗?(不要命名这个函数或任何变量new或任何试图使用它的 C++ 程序员会追捕你)

如果要使用数组索引,可以使用这样的临时指针:

unsigned char *cdata = (unsigned char *)new->data;
cdata[i] = value;

我真的不认为你的方法有问题。如果您期望特定的大小(我认为您确实给出了名称gi8等),我建议包括stdint.h并使用 typedefs uint8_tuint16_tuint32_t.

于 2011-08-04T19:23:07.113 回答
0

指针只是内存空间中的一个地址。您可以根据自己的意愿选择解释它。查看union有关如何以多种方式解释同一内存位置的更多信息。

指针类型之间的强制转换在 C 和 C++ 中很常见,使用 void* 意味着您不希望用户意外取消引用(取消引用 void* 会导致错误,但在强制转换为 int* 时取消引用相同的指针不会)

于 2011-08-04T19:26:10.300 回答