I have this character array
char array[] = {1,2,3}; //FL, FH, Size
and I am trying to access it using pointers in such a way that I get FLFH value together, stored in an integer variable.
I did this
int val =0;
val = *(int*)array;
printf("value of p is %d\n",val);
I was expecting the result to be 12, but it was some 8-digit number which I think maybe the address of the value or something. Could anyone tell me what am I doing wrong here?
It’s never going to give you twelve.
You’re taking two one-byte values and looking at them as if they comprise a single two-byte entity. When you look at them together, you’re re-interpreting their value. The integer
1looks like this, as bits:00000001, and2like this:00000010. The compiler knows how big they are and thus will allow you to access them as individuals, but they’re laid out in order in your array, right next to each other in memory.Inspect the two bytes together as if they were an
int, and you have:0000000100000010, whose value is not 12; it’s 513.For your further reading, what you’re doing is a kind of “type punning”.