填充在C结构 [英] Padding in structures in C

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

问题描述

这是一个面试问题。直到现在,我常想这样的问题纯粹是编译器相关的,应该不用担心我,但现在,我比较好奇吧。

This is an interview question. Till now, I used to think such questions were purely compiler dependent and shouldn't worry me, but now, I am rather curious about it.

假设你给出两种结构为:

Suppose you are given two structures as:

struct A {  
  int* a;  
  char b;  
 }  

struct B {  
  char a;  
  int* b;  
}  

那么,哪一个你会preFER,为什么?
我的回答了这样的(虽然我有些在黑暗中拍摄),该第一结构应preferred因为编译器在字大小的一些倍数(一个结构,它的指针的大小分配空间 - 4字节在32位机和8个字节的64位的)。因此,对于这两种结构,编译器将分配的8个字节(假设它是一个32位计算机)。但是,在第一种情况下,填充将是我所有的变量(即,之后A和B)之后进行。因此,即使由于某种原因,B获取溢出,破坏我的下一个字节填充一定的价值,但我的一个仍然是安全的。

So which one would you prefer and why? My answer went like this (though I was somewhat shooting in the dark) that the first structure should be preferred since the compiler allocates space for a structure in some multiples of the word size (which is the size of the pointer - 4 bytes on 32 bit machines and 8 bytes on 64 bit ones). So, for both the structures the compiler would allocate 8 bytes(assuming its a 32 bit machine). But, in the first case, the padding would be done after all my variables(i.e. after a and b). So even if by some chance, b gets some value that overflows and destroys my next padded bytes, but my a is still safe.

他并没有显得非常高兴,并要求在第二个第一结构的一个缺点。我没有什么好说的。 :D

He didn't seemed much pleased and asked for one disadvantage of the first structure over the second. I didn't have much to say. :D

请帮我解答。

推荐答案

我不认为有任何这种结构的优势。有在这个等式酮(!)恒定。该结构的成员的顺序是保证的声明。

I don't think there's an advantage for any of this structures. There is one(!) constant in this equation. The order of the members of the struct is guaranteed to be as declared.

所以,如果像下面这样,第二个结构的可能有优势,因为它可能有更小的尺寸,但不是在你的榜样,因为他们可能会具有相同的尺寸:

So in case like the following, the second structure might have an advantage, since it probably has a smaller size, but not in your example, as they will probably have the same size:

struct {
    char a;
    int b;
    char c;
} X;

VS

struct {
    char a;
    char b;
    int c;
} Y;

关于下面的评论更多的解释:

所有下面不是100%,但常见的方式的结构将在32位的系统,其中,int是32位被构造

All the below is not a 100%, but the common way the structs will be constructed in 32 bits system where int is 32 bits:

结构体X:

|     |     |     |     |     |     |     |     |     |     |     |     |
 char  pad    pad   pad   ---------int---------- char   pad   pad   pad   = 12 bytes

结构Y:

|     |     |     |     |     |     |     |     |
 char  char  pad   pad   ---------int----------        = 8 bytes

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

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