简体   繁体   中英

Use struct pointer to assign array

I have the following code

typedef struct
    {
        int a;
        int b;
    }DATA;


int _tmain(int argc, _TCHAR* argv[])
{
    DATA *N = NULL;
    unsigned char buff[65536];
    N = (DATA*)&buff;
    N->a = 1000;
    N->b = 50000;
    for(int i =0; i < 8; i ++)
        printf("buff[%d]: %d\n", i, buff[i]);

    return 0;
}

Which renders the following output:

buff[0]: 232

buff[1]: 3

buff[2]: 0

buff[3]: 0

buff[4]: 80

buff[5]: 195

buff[6]: 0

buff[7]: 0

Can anybody tell me in which way the buff Array got assigned ?

You can think of pointers as type-size specifiers. A pointer is roughly an address associated with a size to consider when dereferencing. When declaring int c = 2; int *p = &2; int c = 2; int *p = &2; you are associating the size of an int (say 4bytes) with an address the compiler will define. When you actually dereference p, int x = *p , the compiler knows you are trying to access 4bytes at address p. Now, if you succeed in thinking of it this way, why your buffer gets filled this way will be as clear as ever. Your unsigned char array is a buffer of 65536 bytes. When you cast the address 'buff' into a (DATA *), you are specifying a new size (the size of type DATA) for dereferencing. Therefore, 1000 will be written on the 4bytes of N->a and 50000 on the 4bytes of N->b. Now, 1000 in decimal is 3E8 in hex; since 4bytes need to be written, it will be sign extended and will be written bytes 00, 00, 03, E8, which in decimal is, as you would expect, bytes 0, 0, 3, 232. Now you might think they were written in reverse order, but this is because of endianess. Endianess is the way the processor actually writes bytes into memory, and in your case, your processor writes and reads bytes in reverse order, hence they are put in memory in this order. Same goes for N->b, as 50000 in decimal equals to the decimal bytes, 0, 0, 195, 80.

You wrote two 4-byte integers into the buffer in little-endian format. The program is behaving exactly as expected.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM