1

As far as I know, in C programming language, an array is stored on the memory element by element. (i.e., 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?

2
  • On most computers, the byte order will be opposite from what you assumed. Commented Apr 30, 2012 at 17:43
  • Related: stackoverflow.com/q/29969049/694576 Commented Apr 30, 2015 at 13:54

1 Answer 1

5

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.
Sign up to request clarification or add additional context in comments.

4 Comments

Also, what it prints depends on the endian-ness on this box.
Re "You will get one of two different results depending on endianness." Not just two. There are still some mixed endian boxes around. E.g., 0x2143 or 0x3412.
@OliCharlesworth: Yes. Thanks. It worked great. And the endianness of my platform (visual studio) was: 00000100 00000011 00000010 00000001. I think it is called "little endian".
Is it possible do this conversion with a implementation-independent approach? maybe writing a function which iterate over each bit of the unsigned char array and return a `long int´ type?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.