C cast from uint32_t * to void *

I have a question about casting a pointer for C.

if I have a function with this signature:

uint8_t input_getc(void)

which reads user data from STDIN.

Then I have a pointer

void* buffer

that I store return values ​​from input_getc() in. What would be the right way to do 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 the same?

thanks

+4
source share
3 answers

As of now, none of these methods will compile. Since buffer is void* , you cannot do arithmetic because it has an unknown size.

It is not clear exactly where you are trying to save it. If you are just trying to save uint8_t in the memory location pointed to by buffer with offset i , then this can be done as follows:

 ((uint8_t*)buffer)[i] = temp; 

EDIT:

Well, apparently, void* arithmetic is allowed in C, but not in C ++. However, by doing this, it is still considered unsafe behavior.

See this question: Pointer arithmetic for void pointer in C

+8
source

One way to do this:

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

I do not understand what you mean by

  copying to `void* buffer` 

but if you do the following, then path1 is correct

 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 add + i offcet with void * buffer and yet the whole result is void *, then you attribute the exact result with uint8_t *, then add this value to make it work

but in path2 you add + i offcet with void * buffer, yet the whole result is invalid * and then you get this value ... which is completely wrong. you will get a warning / error here

  warning: dereferencing 'void *' pointer 

Another Edit:

you cannot dereference the void * pointer, but you can perform an arithmetic operation on the pointer value (not its pointe value)

+2
source

Source: https://habr.com/ru/post/1381620/


All Articles