size of a struct in c equals to 1
For some reason if I try to get the actual size of mystruct
I keep getting size 1.
I know that mystruct
is holding the data cause I can dump it out and everything is in mystruct
.
What could be the reason of getting size 1? Thanks
// fragments of my code
struct mystruct {
char *raw;
int count;
};
struct counter {
int total; // =开发者_运维问答 30
}
static struct mystruct **proc()
{
int i = 0;
gchar *key,*val;
struct mystruct **a_struct;
struct counter c;
a_struct = (struct mystruct **)malloc(sizeof(struct mystruct *)*c.total);
while (table (&iter, (gpointer) &key, (gpointer) &val)) {
a_struct[i] = (struct mystruct *)malloc(sizeof(struct mystruct));
a_struct[i]->raw = (char*)key;
a_struct[i++]->count = (int)val;
}
size_t l = sizeof(a_struct) / sizeof(struct mystruct*);
printf("%d",l); // outputs 1
}
You're doing a couple things wrong. First, you're taking sizeof(a_struct)
which is going to be the size of a pointer (since that's what a_struct
is) and then dividing by the size of another pointer. Guaranteed 1.
Besides that, why are you doing a division at all? What I think you want is:
size_t l = sizeof(struct mystruct);
or
size_t l = sizeof(**a_struct);
Edit:
I think I see the reason for your division now; you're trying to find the size of that array. That's not going to work - sizeof
can only work at compile time in C (with some special exceptions in C99 which don't apply to your code), so it can't figure out the size of a dynamic array like that.
you're dividing the size of a pointer by the size of a pointer.
a_struct
is a double pointer to struct mystruct
.
struct mystruct *
is a pointer to struct mystruct
.
Both there sizes will be same.
Do this size_t l = sizeof(struct mystruct);
You are taking the size of two pointers and dividing one by the other,
size_t l = sizeof(a_struct) / sizeof(struct mystruct*);
a_struct
is declared as struct mystruct **a_struct
so this is the same as saying
size_t l = sizeof(struct mystruct **) / sizeof(struct mystruct*);
since all pointers have the same size, ** is the same size as *, so this will always evaluate to 1.
I'm not quite sure what you are trying to print out here, the size of a_struct
? or the total allocation size? The size of a_struct
is just c.total
, the total allocation is the sum of all of the values that you passed to malloc.
精彩评论