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
bufferis 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_tinto the memory location pointed bybufferwith 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