解引用空指针 [英] Dereferencing void pointers

查看:189
本文介绍了解引用空指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在更好地了解答案的希望
给这个岗位,可有人请向我解释,如果
以下循环缓冲器实现是可能的,并且如果
没有,原因为何。

In the hope of gaining a better understanding of the answers given in this post, can someone please explain to me if the following circular buffer implementation is possible, and if not, why not.

#define CB_TYPE_CHAR     0
#define CB_TYPE_FLOAT    1

...

typedef struct CBUFF
{
    uint16 total;       /* Total number of array elements */
    uint16 size;        /* Size of each array element */
    uint16 type;        /* Array element type */
    uint16 used;        /* Number of array elements in use */
    uint16 start;       /* Array index of first unread element */
    void *elements;     /* Pointer to array of elements */
} CBUFF;

...

void cbRead(CBUFF *buffer, void *element)
{
    if (buffer->type == CB_TYPE_CHAR)
    {
    /* The RHS of this statement is the problem */
        *(char*)element = *(buffer->elements[buffer->start]);
    }

    /* Other cases will go here */

    buffer->start = (buffer->start + 1) % buffer->total;

    --buffer->used;
}

据我所知,LHS必须转换为char这样我就可以
取消引用无效指针。我也明白,这code
片段:

I understand that the LHS must be cast to char so that I can dereference the void pointer. I also understand that this code fragment:

buffer->elements[buffer->start]

给出的元件的'buffer->启动'元素的地址
阵列,这也是我想提领,以获得对
该地址的内容。或者说,至少这是我从拿
K&安培;:R

gives the address of the 'buffer->start' element of the elements array, which I also want to dereference in order to get to the content of that address. Or at least that's what I take from K&R.

鉴于这一切,我怎么告诉编译器的内容
在该地址的内存是一个char,而且它是没关系
解引用呢?有一些事情在这里,我只是不
明白了。

Given all that, how do I tell the compiler that the content of the memory at that address is a char, and that it is okay to dereference it? There is something going on here I just don't understand.

推荐答案

buffer->元素也有无效* ,所以你需要转换它之前,你可以用它做任何事情:

buffer->elements is also a void * so you need to cast it before you can do anything with it:

*(char*)element = ((char *)buffer->elements)[buffer->start];

这篇关于解引用空指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆