是内存对齐不同的不同的数据类型 [英] Is the memory alignment different for different data types

查看:152
本文介绍了是内存对齐不同的不同的数据类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

和C中的不同的数据类型,如char,short,int和长,浮动,双有不同的内存对齐的边界?在32位字对齐的字节寻址的操作系统,如何访问一个char或访问一个整数或浮点数短的有什么不同?在这两种情况下,不会在CPU读取一个完整的32位字?当一个int是不是在边界会发生什么?它是如何能够读取字符在任何内存地址?

Do different data types in C such as char, short, int, long, float, double have different memory alignment boundaries? In a 32 bit word aligned byte addressable operating system, how is accessing a char or short different from accessing an int or float? In both cases, does the CPU read a full 32-bit word? What happens when an int is not at the boundary? How is it able to read a char at any memory address?

推荐答案

简短的回答,正如其他人指出的那样,是编译器会做什么是最适合的架构它编译成。它可以调整他们的本地字大小。也可能不是。这里是一个示例程序演示了这一点:

The short answer, as others have pointed out, is the compiler will do what's best for the architecture it's compiling to. It may align them to the native word size. It may not. Here is a sample program demonstrating this point:

#include <iostream>

int main()
{
    using namespace std;

    char c;
    short s;
    int i;

    cout << "sizeof(char): " << sizeof(char) << endl;
    cout << "sizeof(short): " << sizeof(short) << endl;
    cout << "sizeof(int): " << sizeof(int) << endl;

    cout << "short is " << (int)&s - (int)&c << " bytes away from a char" << endl;
    cout << "int is " << (int)&i - (int)&s << " bytes away from a short" << endl;
}

输出:

sizeof(char): 1
sizeof(short): 2
sizeof(int): 4
short is 1 bytes away from a char
int is 4 bytes away from a short

正如你所看到的,它增加了int和短期之间的一些填充。它没有理会短。在其他情况下,反向可能是真的。优化的规则很复杂。

As you can see, it added some padding between the int and the short. It didn't bother with the short. In other cases, the reverse may be true. Optimization rules are complex.

和,警告:编译器是比你聪明。不要填充和对齐播放,除非你有一个非常,非常好的理由。只是相信,什么编译器做的是正确的事。

And, a warning: The compiler is smarter than you. Don't play with padding and alignment unless you have a really, really good reason. Just trust that what the compiler is doing is the right thing.

这篇关于是内存对齐不同的不同的数据类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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