结构和指针 [英] Structure and pointer

查看:93
本文介绍了结构和指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在获取条目存储地址到结构的成员变量时遇到问题.我尝试了两种方法,其中一种无法正常工作.如果你们给我一些建议,那就太好了.

I'm having a problem getting the entry memory address to a member variable of a structure. I've tried in two ways, one of which didn't work properly. It would be very good if you guys give me some advice.

首先,我定义了一个名为BITMAP_HEADER的结构.

First, i defined a structure named BITMAP_HEADER.

struct BITMAP_HEADER
{
    WORD    bfType ;
    DWORD   bfSize ; 
    WORD    bfReserved1 ;
    WORD    bfReserved2 ;
    DWORD   bfOffBits ;
} ;

第二,我定义并初始化了一些变量.在阅读下一行之前,请先查看下面的代码.万一你问我为什么有字符指针,我需要访问整数bfSize的每个字节.

Second, i defined and initialized some variables. please look at the code below before you read next line. In case you ask me why i got a character pointer, i needed to access each bytes of integer bfSize.

struct BITMAP_HEADER    bitmap_header ;
char*                   pSize = (char*)&bitmap_header.bfSize;

第三,我以两种不同的方式获得了bfSize的内存地址,并打印了值.

Third, i got a memory address to the bfSize in two different ways and printed the values.

1. printf("%X\n", *pSize) ;
2. printf("%X\n", (unsigned char)*(((char*)&bitmap_header)+2)) ; 

(1)直接获得了到bitmap_header.bfSize的内存地址.

(1) directly got a memory address to the bitmap_header.bfSize.

(2)获得了一个指向结构BITMAP_HEADER的内存地址,并将指针移至下一个2个字节.

(2) got a memory address to the structure BITMAP_HEADER and shifted the pointer to the next by 2 bytes.

最后,这是结果.

2D
F6

供您参考,这是结构BITMAP_HEADER的十六进制数据.

For your information, here is the hex data of the structure BITMAP_HEADER.

42 4D / F6 C6 2D 00 / 00 00 / 00 00 / 36 00 00 00

为什么第一种方法不起作用?我以为两种方法完全一样.

Why didn't the first method work? I thought the two methods were exactly same.

推荐答案

您在这里遇到了结构填充.编译器正在bfTypebfSize字段之间插入两个字节的填充值,以将bfSize对齐为4个字节的大小,因为bfSize是DWORD.

You're running into structure padding here. The compiler is inserting two bytes' worth of padding between the bfType and bfSize fields, to align bfSize to 4 bytes' size, since bfSize is a DWORD.

通常来说,您不能依靠能够计算结构内的精确偏移量,因为编译器可能会在成员之间添加填充.您可以使用特定于编译器的位在某种程度上控制它.例如,在MSVC上,打包实用程序,但我不建议这样做.可以使用结构填充来指定成员对齐限制,并且某些体系结构会在未对齐访问时发生故障. (其他人可能会手动修复对齐方式,但通常而不是很慢. )

Generally speaking, you cannot rely on being able to calculate exact offsets within a structure, since the compiler might add padding between members. You can control this to some degree using compiler-specific bits; for example, on MSVC, the pack pragma, but I would not recommend this. Structure padding is there to specify member alignment restrictions, and some architectures will fault on unaligned accesses. (Others might fixup the alignment manually, but typically do this rather slowly.)

另请参见: http://en.wikipedia.org/wiki/Data_structure_alignment#Data_structure_padding

这篇关于结构和指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆