C 从 uint32_t* 转换为 void *
我有一个关于 C 指针转换的问题。
如果我有一个具有以下签名的函数:
uint8_t input_getc(void)
,
它从 STDIN 读取用户输入。
然后我有一个指针
void* buffer
,用于存储来自 input_getc()
的返回值。转换它的正确方法是什么?
//read user input
for(i = 0; i < SIZE; ++i)
{
uint8_t temp = input_getc();
//copy to void* buffer
*(uint8_t *)(buffer + i) = temp //WAY #1
*(buffer + i) = (void *)temp; //WAY #2
}
这两个是一样的吗?
谢谢
I have a question about pointer casting for C.
if I have a function with this signature:
uint8_t input_getc(void)
which reads user input from STDIN.
Then I have a pointer
void* buffer
that I store return values from input_getc()
in. What would be the proper way to cast this?
//read user input
for(i = 0; i < SIZE; ++i)
{
uint8_t temp = input_getc();
//copy to void* buffer
*(uint8_t *)(buffer + i) = temp //WAY #1
*(buffer + i) = (void *)temp; //WAY #2
}
Are both of these the same?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我不明白你的意思,
但如果你正在做以下事情,那么 way1 是正确的
大编辑:
IN WAY1
你正在添加 +i offcet 与 void * buffer 和仍然整个结果是 void* 然后你用 uint8_t* 类型转换整个结果然后访问该值,这样它就可以工作
但是在 way2 中你用 void * buffer 添加 +i offcet 仍然整个结果是 void* 并且那么您正在访问该值...这是完全错误的..
您将在此处收到警告/错误
再编辑一次:
您不能取消引用 void* 指针,但可以使用指针值(而不是其指针值)进行算术运算
i am not understanding what do you mean by
but if you are doing following thing then way1 is right
BIG Edit :
IN WAY1
you are adding +i offcet with void * buffer and still whole result is void* then you are typecasting that whole result with uint8_t* then accesing that value so it works
but in way2 you are adding +i offcet with void * buffer still whole result is void* and then you are accesing that value ...which is completely wrong..
you will get warning/error here
One more Edit :
you can not dereferencing void* pointer but you can do arrithmetic operation with pointer value (not its pointe value)
就目前而言,这些方法都无法编译。由于
buffer
是一个void*
,因此您无法对其进行算术运算,因为它的大小未知。目前尚不完全清楚您尝试将其存储在何处。如果您只是尝试将
uint8_t
存储到buffer
指向的内存位置,偏移量为i
,那么可以这样做:编辑:
好吧,显然 C 中允许对 void* 进行算术运算,但 C++ 中不允许。但这样做仍然被认为是不安全的行为。
请参阅此问题:C 中 void 指针的指针算术
As it is right now, neither of those methods will compile. Since
buffer
is avoid*
you can't do arithmetic on it since it has an unknown size.It's not entirely clear exactly where you are trying to store it. If you're just trying to store the
uint8_t
into the memory location pointed bybuffer
with offseti
, then it can be done like this:EDIT :
Okay, apparently arithmetic on
void*
is allowed in C, but not in C++. However, doing so it still considered unsafe behavior.See this question: Pointer arithmetic for void pointer in C
一种方法是:
One way to do this is: