简体   繁体   中英

Converting unsigned char array to an integer

As far as I know, in C programming language, an array is stored on the memory element by element. (ie, element 0, element 1, element 2, ... , element n). I'm trying to see that with the following code:

unsigned char a[] = { '\1' , '\2', '\3' ,'\4' };  
printf("%d\n", (int*) a);

Since unsigned char is 1 byte and an integer is 4 bytes; I thought it has to print the value:

00000001 00000010 00000011 00000100 = 2^2 + 2^8 + 2^9 + 2^17 + 2^24 = 16909060

However, when I run this program, it generates different results for every trials.

What am I missing here?

You probably want to use *(int *)a , otherwise you're just printing an address.

However, this will invoke implementation-defined behaviour:

  • You will get a different result depending on the endianness of your platform.
  • Depending on the platform, the char array may not be properly aligned to be read as an int .
  • The compiler may perform funky optimizations based on assumptions that you will never read the char array through an int * - you are breaking what are known as the strict aliasing rules.

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