简体   繁体   中英

cast void type pointer in an array

Suppose I have an Uint array: Uint myarray[10] . Uint is unsigned 16 bit integer. I also define an void type pointer such that

void * arrayHandle = &myarray;

Add some offset such that arrayHandle points to myarray[3] (mark here, will change offset in another test)

arrayHandle = (Uint *)arrayHandle + 3;

Then assign a 32 bit float type data to memory where arrayHandle points to

*((float *)arrayHandle) = 1234.5678;

32 bit 1234.5678 can be expressed as two 16 bit Uint raw data, where the higher 16 bit in decimal is 21035, and the lower 16 bit in decimal is 17562.

After all, I go to check the array and find myarray[2] = 21035 and myarray[3] = 17562 .

However, when I go back to change the offset such that arrayHandle points to myarray[2]

arrayHandle = (Uint *)arrayHandle + 2;

And do the similar float assignment. I find that myarray[2] = 21035 and myarray[3] = 17562 .

The array content is exactly the same! Can anyone tell me why?

Then assign a 32 bit float type data to memory where arrayHandle points to

 *((float *)arrayHandle) = 1234.5678; 

Stop here, you are actually breaking strict aliasing rule , thus yielding an UB (so anything can happen). Even if arrayHandle is of type void * , it originates from myarray , that is declared as unsigned integer type.

Use array of unions for type punning between integer and floating-point types.

数组已经是一个指针,请尝试使用void * arrayHandle = myarray ;

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