1

I saw a video lecture about arrays and the lecturer said the output result of

int arr[5];
arr[3}=128;
((short *)arr)[6]=2;
cout << arr[3] << endl;

would be 512+128. I implement the code on my text editor, but after compile and run it the output is 2. My doubt is if my code is not correct or if the instructor is somehow wrong (or if I am misunderstanding some aspect).

My code:

#include <stdio.h>
int main(){
int array[5];
array[3]=128;
((short*)array)[6]=2;
printf("%d\n", array[3]);
return 0;
}
3

1 Answer 1

3

the lecturer said the output result of [this code snippet] would be 512+128

The lecturer should have mentioned a few other things in order for the above to be true:

  • The result is dependent on hardware, which is big endian
  • The result is dependent on using a specific C compiler, with 16-bit ints and 8-bit shorts.

Otherwise, the result is not going to be the same.

My doubt is if my code is not correct or if the instructor is somehow wrong

The instructor is right, and your code is correct, but you are running this code on different platforms.

The main lesson that you should learn from this experiment is that code like that is fundamentally non-portable. If you wish to make it portable, use types from stdint.h to avoid sizing issues, and use bit manipulation instead of partial writes to avoid endianness problems.

Sign up to request clarification or add additional context in comments.

3 Comments

still not understanding why on my machine the output is 2. If I'm changing the value of "short 6" , doesn't that imply that array[3] remains with value 128? I mean, "short 6" is inside array[2] , right? Can you help me? How do I know my machine's endieness?
@cooper You probably have a 32-bit, little endian platform with 16-bit shorts. Because of this, int values that are smaller than 16 bits would be the same when you retrieve them from the same address as 32 or 16 bits. The best exercise to do would be drawing your int array as 20 adjacent squares (4 bytes per int), writing the value 128 into square 12 (zero-based; bytes 13, 14, and 15 are zeros) and then looking at the content of bytes 12 and 13 - the two bytes of short at index 6. They would have 128 before the replacement, and 2 after the replacement.
@cooper Another useful exercise is to replace values with something that occupies the entire 32/16 bits, and see what's going to happen (demo).

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.