Typecasting an Array

Jan 28, 2008 at 3:40pm
Hello, I just have a question on typecasting an array.
For the code below:

1
2
3
4
5
6
7
8
9
10
#include <iostream>
#include <cstdlib>
using namespace std;
int main() {
char cbuff[32];
short * sbuff = ( short*) &cbuff; 
sbuff[10] = 65;
cout << cbuff[20] ;
cin.get();
}


When I run this on DEV-C++ compiler, the output is 'A'. However, shouldn't the typecasting change the arrays into pairs?
What I thought should happen was: since cbuff[20] and cbuff[21] are paired, when I initialize sbuff[10], the value should go into cbuff[21] first.

Can anyone explain to me what is going on?


Also, if I do a similar typecasting using C, would the answer to my question be any different?

Thank you for your time.
Last edited on Jan 28, 2008 at 4:35pm
Jan 28, 2008 at 6:16pm
Intel processors are "little-endian", meaning that the last byte (the least significant) is stored at the lowest address: so storing 0x0041 at sbuff[10], would mean 0x41 at cbuff[20] and 0x00 at cbuff[21]

Results should not vary depending on whether you use C or C++, but on the platform you compile for.
Jan 28, 2008 at 7:54pm
Thank you so much. Really appreciate it.
Topic archived. No new replies allowed.