简体   繁体   English

使用结构指针分配数组

[英]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 ? 有人可以告诉我buff数组以哪种方式分配吗?

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; int c = 2; int *p = &2; you are associating the size of an int (say 4bytes) with an address the compiler will define. 您正在将一个int的大小(例如4字节)与编译器将定义的地址相关联。 When you actually dereference p, int x = *p , the compiler knows you are trying to access 4bytes at address p. 当您实际取消引用p, int x = *p ,编译器知道您正在尝试访问地址p的4个字节。 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. 您的无符号char数组是65536个字节的缓冲区。 When you cast the address 'buff' into a (DATA *), you are specifying a new size (the size of type DATA) for dereferencing. 当将地址“ buff”转换为(DATA *)时,您将指定新的大小(DATA类型的大小)以进行取消引用。 Therefore, 1000 will be written on the 4bytes of N->a and 50000 on the 4bytes of N->b. 因此,将在N-> a的4个字节上写入1000,在N-> b的4个字节上写入50000。 Now, 1000 in decimal is 3E8 in hex; 现在,小数点后的1000是十六进制的3E8; 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. 由于需要写入4字节,因此将对其进行符号扩展,并将写入字节00、00、03,E8,正如您所期望的,十进制为字节0、0、3、232。现在您可能认为它们是以相反的顺序写,但这是由于耐力。 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. Endianess是处理器实际上将字节写入内存的方式,在您的情况下,您的处理器以相反的顺序写入和读取字节,因此按此顺序将它们放入内存。 Same goes for N->b, as 50000 in decimal equals to the decimal bytes, 0, 0, 195, 80. N-> b也是如此,因为十进制的50000等于十进制字节0、0、195、80。

You wrote two 4-byte integers into the buffer in little-endian format. 您以little-endian格式将两个4字节整数写入缓冲区。 The program is behaving exactly as expected. 该程序的行为完全符合预期。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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