c - 副作用的大小和分配位置

标签 c size malloc

Possible Duplicate:
Why isn’t sizeof for a struct equal to the sum of sizeof of each member?

我不明白为什么会这样:

#include <stdio.h>
#include <stdlib.h>

typedef struct
{
    char b;
    int a;
} A;

typedef struct
{
    char b;
} B;

int main() {
    A object;
    printf("sizeof char is: %d\n",sizeof(char));
    printf("sizeof int is: %d\n",sizeof(int));
    printf("==> the sizeof both are: %d\n",sizeof(int)+sizeof(char));
    printf("and yet the sizeof struct A is: %d\n",sizeof(object));
    printf("why?\n");

    B secondObject;
    printf("pay attention that the sizeof struct B is: %d which is equal to the "
            "sizeof char\n",sizeof(secondObject));

    return 0;
}

我想我已经在代码中解释了我的问题,没有必要再解释了。除此之外我还有一个问题: 我知道在:堆/静态堆/堆栈上有分配,但这意味着分配位置未知,怎么可能?

我正在谈论这个例子:

    typedef struct
{
    char *_name;
    int   _id;
} Entry;

int main()
{
    Entry ** vec = (Entry**) malloc(sizeof(Entry*)*2);
    vec[0] = (Entry *) malloc(sizeof (Entry));
    vec[0]->_name = (char*)malloc(6);
    strcpy (vec[0]->_name, "name");
    vec[0]->_id = 0;
    return 0;
}

我知道: vec 在堆栈上。 *vec 在堆上。 *vec[0] 在堆上。 vec[0]->id 在堆上。

但是: vec[0]->_name 未知 为什么?

最佳答案

结构成员之间和结构末尾有未指定的填充量。在 C 中,结构对象的大小大于或等于其成员大小的总和。

关于c - 副作用的大小和分配位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14662312/

相关文章:

c - 将指针存储在 vector 中

c - 如果 `"转换为 "` exist in `,为什么 `char` %c `int` printf`?

C 扫描远程服务器上的开放端口

c++ - 如何在 C/C++ 中将 12 位图像转换为 8 位图像?

angularjs - Angular : get Dimension from Base64 Image

c - 奇怪的 malloc 行为

c - 错误 : assigning to 'int **' from incompatible type 'int [][]

html - Textarea 对于容器来说太小了。连手动放大都做不到

c++ 通过引用和指针传递参数

c - 在 C 中,如何访问此结构中的元素?