Soundview Soundview - 4 years ago 70
C Question

How can I properly calculate the size of a struct array? Am I doing this right?

I am trying to get the total amount of bytes of an array of structs. The total bytes of 1 struct is 96 bytes. I put the int first to avoid padded bytes. I really don't know if what i'm doing is correct but i know that allocating struct[MAX] would be 96 bytes * 50 based on the sample i pasted here. i get about 7 million bytes, or some garbage value. Anyone can help me calculate in code the amount of

struct address addr[MAX]
where
MAX = 50
. Here is the full sample. Thanks guys!

#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;
}

Answer Source

This line:

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

Is incorrect as allocation is a pointer. To get the total size simply do the following:

#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;
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download