C语言 取消引用空指针
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13694753/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Dereferencing void pointers
提问by Zack
In the hope of gaining a better understanding of the answers given in thispost, 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;
}
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:
我知道必须将 LHS 强制转换为 char 以便我可以取消引用 void 指针。我也明白这个代码片段:
buffer->elements[buffer->start]
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.
给出元素数组的 'buffer->start' 元素的地址,我也想取消引用以获取该地址的内容。或者至少这是我从 K&R 那里学到的。
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.
鉴于所有这些,我如何告诉编译器该地址处的内存内容是一个字符,并且可以取消引用它?这里发生了一些事情,我只是不明白。
回答by Chris Dodd
buffer->elementsis also a void *so you need to cast it before you can do anything with it:
buffer->elements也是 avoid *所以你需要先施放它才能对它做任何事情:
*(char*)element = ((char *)buffer->elements)[buffer->start];
回答by Ed S.
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?
鉴于所有这些,我如何告诉编译器该地址处的内存内容是一个字符,并且可以取消引用它?
Well, you've already done it on the LHS of that line:
好吧,您已经在该行的 LHS 上完成了:
*(char*)element = *(buffer->elements[buffer->start]);
To derefence buffer->elements[n]you will need to cast that as well.
要取消引用,buffer->elements[n]您还需要投射它。
*(char*)element = *((char*)buffer->elements)[buffer->start];
Now the question is whether or not that cast is correct. I can't tell you that as you did not post the initialization of buffer->elements.
现在的问题是这个演员阵容是否正确。我不能告诉你,因为你没有发布buffer->elements.

