main(){
char i[2];
* i = 0;
* (i + 1) = 1;
printf("len = %d \n",sizeof(int *));
printf("i[0] = %d \n",*(int *)i);
}
where the answer is not 16 the answer is 256 i use the turboc2.0 the hex is 100
main(){
char i[2];
* i = 0;
* (i + 1) = 1;
printf("len = %d \n",sizeof(int *));
printf("i[0] = %d \n",*(int *)i);
}
where the answer is not 16 the answer is 256 i use the turboc2.0 the hex is 100
This code depends on your system, specifically on the size of an int.
After initializing, your i
array looks like this:
------------
|0x00 | 0x01 |
------------
Assumed an int
is 32 bits on your system:
When casting i
to an *int
and dereferencing it, there will be four bytes which are accessed (since an int
is 32 bits or four bytes):
--------------------------
|0x00 | 0x01 | 0x?? | 0x?? |
--------------------------
So, the last two bytes are out of bounds of your array, will have any value, and you will observe undefined behavior (on my system, actually, it prints different values each time I execute the code, like 1762656512
, -375848704
, ...).
Assumed an int
is 16 bits on your system, it gets a littlebit "better":
In this case, when casting i
to an *int
and dereferencing it, the two bytes will be accessed as a 16 bit value. But, it then still depends on the endianess which value you get:
Little endian: *(int*) i = 0x0100 = 256
Big endian: *(int*) i = 0x0001 = 1
So, if you expect 256
, you need to make sure to be on a little endian 16 bit system ...
BTW: When using sizeof()
with printf()
, make sure to use the %zu
format specifier.