如何正确计算结构数组的大小?我这样做了吗?

时间:2017-02-05 20:49:42

标签: c memory-management struct malloc

我正在尝试获取结构数组的总字节数。 1个结构的总字节数为96个字节。我把int放在第一位以避免填充字节。我真的不知道我所做的事情是否正确,但我知道根据我在这里粘贴的样本,分配struct [MAX]将是96字节* 50。我得到大约700万字节,或一些垃圾值。任何人都可以帮助我在代码中计算struct address addr[MAX] MAX = 50的数量。这是完整的样本。多谢你们!

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


#define MAX 50  //for structure

struct address {
     int zip;   // 4 bytes
     char name[20];      // 20 bytes
     char street[40];    // 40 bytes
     char city[16];      // 16 bytes
     char state[4];      // 4 bytes
     char country[10];   // 10 bytes
};

int main()
{
    struct address addr[MAX];
    unsigned int *allocation;
    allocation = malloc(MAX * sizeof(struct address));

    if (!allocation) {
        printf("Memory allocation error\n\n");
        exit(1);
    } else {
        printf("address start: 0x%x08 - size in bytes: %d\n", &addr, sizeof(struct address));
        printf("sizeof zip %d\n", sizeof(addr[0].zip));
        printf("sizeof name %d\n", sizeof(addr[0].name));
        printf("sizeof street %d\n", sizeof(addr[0].street));
        printf("sizeof city %d\n", sizeof(addr[0].city));
        printf("sizeof state %d\n", sizeof(addr[0].state));
        printf("sizeof country %d\n", sizeof(addr[0].country));
        printf("total size of structure is %d\n", allocation);
    }

    free(allocation);
    system("PAUSE");
    return 0;
}

2 个答案:

答案 0 :(得分:1)

这一行:

   printf("total size of structure is %d\n", allocation);

不正确,因为allocation是一个指针。要获得总大小,请执行以下操作:

#include <stdio.h>

#define MAX 50  //for structure

struct address{
     int zip;   // 4 bytes
     char name[20];      // 20 bytes
     char street[40];    // 40 bytes
     char city[16];      // 16 bytes
     char state[4];      // 4 bytes
     char country[10];   // 10 bytes
};

int main()
{
    struct address addr[MAX];
    printf("Size %zu\n", sizeof(addr));
    return 0;
}

答案 1 :(得分:0)

struct address addr[MAX]

使用此行从addr [0]分配结构到addr [49]