简体   繁体   English

解引用中的指针查询

[英]pointer query in dereferencing

typedef unsigned char uint8_t;
typedef int uint32_t;

uint8_t Local_Buffer[2] = {1,3};

uint32_t d_buffer;

d_buffer = ( *(uint32_t *)Local_Buffer );

What is the content of d_buffer in the end? d_buffer的内容到底是什么? After printing value of d_buffer, i get 0x70820301. 打印d_buffer的值后,我得到0x70820301。 So its an address. 所以它是一个地址。

You're setting up a local buffer of 2 bytes with the values 1, 3, like this: 您正在设置一个2字节的本地缓冲区,其值为1、3,如下所示:

|0x01|0x03|

Then you're casting that value (using C -style casts) to a pointer to a uint32_t , dereferencing that and stroing the result. 然后,您将该值(使用C样式强制转换)转换为指向uint32_t的指针,并对其进行解引用并存储结果。 uint32_t is 4 bytes in size. uint32_t大小为4个字节。

Logically, it may seem that you are getting d_buffer to have some values like: 从逻辑上讲,您似乎正在使d_buffer具有一些值,例如:

|0x01|0x03|?|?

In reality, this cast reads past the ends of an array, and therefore evokes undefined behavior, so literally anything could happen. 实际上,此强制转换会读取数组的末尾,因此会引起未定义的行为,因此实际上任何事情都可能发生。

In your particular case, it appears you're getting d_buffer populated with the expected values (0x03,0x01) along with two other "random" values from the adjacent memory address. 你的具体情况,看来你要d_buffer填写了与其他两个“随机”,从相邻的存储地址值沿着预期值(0x03,0x01)。

The endianness of your architecture will tell you how the individual bytes are stored to make up the value of your uint32_t value. 您的体系结构的字节序将告诉您如何存储各个字节以构成uint32_t值的值。 Your value of 0x70820301 shows that 0x0301 are stored as expected, along with the "unexpected" garbage values of 0x70820000 . 您的值0x70820301显示0x0301与预期的存储值以及0x70820000的“意外”垃圾值0x70820000

( *(uint32_t *)Local_Buffer ); here Local_Buffer decays to unsigned char* , which points to the first element of the array. 这里Local_Buffer衰减为unsigned char* ,它指向数组的第一个元素。 You are casting it to int* and then de-referencing it. 您将其强制转换为int* ,然后取消引用。 You code has Undefined Behavior , since the array is of size 2, where an int has in most platform atleast size 4. Accessing it as int will pass beyond the memory, and what will happen while accessing that memory is undetermined . 您的代码具有Undefined Behavior ,因为该数组的大小为2,其中int在大多数平台上的大小至少为4。以int访问它将超出内存,并且访问该内存时发生的情况不确定

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

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