我正在尝试获取结构数组的总字节数。1 个结构的总字节数为 96 个字节。我把 int 放在第一位以避免填充字节。我真的不知道我正在做的是否正确,但我知道根据我粘贴在此处的示例分配 struct[MAX] 将是 96 字节 * 50。我得到大约 700 万个字节,或者一些垃圾值。任何人都可以帮我在代码中计算MAX = 50
struct address addr[MAX]
的数量.这是完整的示例。谢谢大家!
#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 errornn");
exit(1);
} else {
printf("address start: 0x%x08 - size in bytes: %dn", &addr, sizeof(struct address));
printf("sizeof zip %dn", sizeof(addr[0].zip));
printf("sizeof name %dn", sizeof(addr[0].name));
printf("sizeof street %dn", sizeof(addr[0].street));
printf("sizeof city %dn", sizeof(addr[0].city));
printf("sizeof state %dn", sizeof(addr[0].state));
printf("sizeof country %dn", sizeof(addr[0].country));
printf("total size of structure is %dn", allocation);
}
free(allocation);
system("PAUSE");
return 0;
}
这一行:
printf("total size of structure is %dn", 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 %zun", sizeof(addr));
return 0;
}
struct address addr[MAX]
使用此行,您将结构从 addr[0] 分配给 addr[49]