Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C casting from uint32_t* to void *

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

like image 234
Hunter McMillen Avatar asked Dec 17 '22 07:12

Hunter McMillen


2 Answers

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

like image 146
Mysticial Avatar answered Dec 26 '22 02:12

Mysticial


One way to do this is:

*(((uint8_t*)buffer)+i) = temp;
like image 36
Jason Kuang Avatar answered Dec 26 '22 02:12

Jason Kuang