Is it safe to read and write on an array of 32 bit data byte by byte?

114 Views Asked by At

So I have a void * data of 32 bit unsigned integers which represents the pixels. Is it okay for me to access one of the pixels with a char * and modify the values directly? Or is it better to store my new pixel in a temporary uint32_t variable and then assign with the correct pointer dereferencing or at least memcpy?

Will I have problems with memory alignment or possibly performance depending on the hardware platform?

2

There are 2 best solutions below

0
On BEST ANSWER

Yes, this is correct. The only danger would be generating a bit pattern that does not correspond to any int, but on modern systems there are no such patterns. Also, if the data type was uint32_t specifically, those are prohibited from having any such patterns anyway.

Note that the inverse situation of using a uint32_t to write multiple chars at once is not permitted (strict aliasing rule).

0
On

Yes, it's fine.

Arrays don't have unused bytes inside them, so if you use uint32_t you can be sure that each element uses exactly 32 bits.