Pointer arithmetic around cast
c, casting, pointer-arithmetic
Solution
Let's take it step by step. Your expression can be decomposed like this:
((short*)(((char*) (&arr[1])) + 8))[3]
-----------------------------------------------------
char *base = (char *) &arr[1];
char *base_plus_offset = base + 8;
short *cast_into_short = (short *) base_plus_offset;
cast_into_short[3] = 100;
`base_plus_offset` points at byte location `12` within the array. `cast_into_short[3]` refers to a `short` value at location `12 + sizeof(short) * 3`, which, in your case is `18`.
Problem
I am currently enrolled in a CS107 class which makes the following assumptions: - `sizeof(int) == 4` - `sizeof(short) == 2` - `sizeof(char) == 1` - big endianness My professor showed the following code: ``` int arr[5]; ((short*)(((char*) (&arr[1])) + 8))[3] = 100; ``` Here are the 20 bytes representing `arr`: ``` |....|....|....|....|....| ``` My professor states that `&arr[1]` points here, which I agree with. ``` |....|....|....|....|....| x ``` I now understand that `(char*)` makes the pointer the width of a char (1 byte) instead of the width of an int (4 bytes). What I don't understand is the `+ 8`, which my professor says points here: ``` |....|....|....|....|....| x ``` But shouldn't it point here, since it is going forwards 8 times the size of a char (1 byte)? ``` |....|....|....|....|....| x ```