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
As it is right now, neither of those methods will compile. Since buffer
is a void*
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 by buffer
with offset i
, then it can be done like this:
((uint8_t*)buffer)[i] = temp;
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:
*(((uint8_t*)buffer)+i) = temp;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With