Pointer offset appreciated

Today brush problems encountered when a question is as follows:

int main() {
    int array[2019] = { 0 };
    array[19] = 2019;
    unsigned long offset = (unsigned long)((short*)array + 2019) - (unsigned long)(array + *(unsigned char*)(array + 19));
    cout << offset;
}

The output of the above program is how much?

Look closely, there is a variety of pointer manipulation, people will have to give up the urge to glance. In fact, do not worry, pumping cocoon stripping wire in accordance with one level, in fact, is not so difficult.
First, ((short*)array+2019)in, is the arraypointer to a intpointer type cast shortpointer type, then the offset 2019 units. shortType 2 bytes, so that in the offset address 2019 * 2 = 4038;
then, for the latter *(unsigned char*)(array + 19)decomposition: 1, array+19corresponding to a get array[19]address, this address is stored as the number 2019, which is written in hexadecimal 0x000007E3, and (unsigned char*)(array + 19)is this address into a unsigned charpointer type, because the chartype only one byte, so its address taken out of the count only the original data stored in memory before 1/4, that is E3, about why E3, instead of 00it? This place say below. Therefore, *(unsigned char*)(array + 19)although the char type, but it is converted to a number 0xE3, i.e., 227. After then (unsigned long)(array + *(unsigned char*)(array + 19))equivalent to the address offset array unit 227, an offset 227 * 4 = 908. Therefore output offset = 4038 - 908 = 3130.

Why on the above it is E3rather than 00what?

This is because in the memory storage, in accordance with the stored bytes from low to high, the tests are as follows:

int main{
    int i = 2019;
    unsigned char *c;
    c = (unsigned char *)&i;
    printf("内存中存储情况:\n");
    for (int n = 0; n < 4; n++)
        printf("  0x%x\t%02x\n", &i + n, c[n]);
    printf("实际的16进制形式:\n");
    printf("  0x%08x\n", i);
    return 0;
}

The output is:

Guess you like

Origin www.cnblogs.com/hellovan/p/11406986.html
Recommended