Search code examples
c++cmallocvoid-pointersmemset

Read/Write a single byte of a void* variable


If I have

void *temp = malloc(128);
memset(temp, 0 , 128);  

And I want to read the first byte alone, following is what I'm doing.

char a[2];
strncpy(a, (char*)temp, 1);
int p = a[0];
//p will be zero in this case

Q1. I'm sure there is a more elegant way to achieve the same. If so, what would it be?

Q2. Is there a way I can alter the value of that single byte alone?

Say I want the first byte to have the value equivalent to the int value 48 (i.e. 00110000) How would I do that? I was able to make no progress with the write.


Solution

  • you can cast it to char * then access the memory

    char *buff = temp;
    char p = buff[0]; // read first byte