简体   繁体   中英

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

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

一种方法是:

*(((uint8_t*)buffer)+i) = temp;

i am not understanding what do you mean by

 copying to  `void* buffer`

but if you are doing following thing then way1 is right

int main()
{
    int i;
    char a[10];
    void *buffer;
    buffer = &a;   // buffer is void* type pointer and its pointing to some buffer then
    for(i = 0; i < 10; ++i)
    {
        uint8_t temp = 65;

        //copy to void* buffer
        *(uint8_t *)(buffer + i) = temp; //WAY #1

    }
    printf("\n %s",a);
}

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

 warning: dereferencing ‘void *’ pointer

One more Edit :

you can not dereferencing void* pointer but you can do arrithmetic operation with pointer value (not its pointe value)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM