tags:

views:

162

answers:

4

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
}
+4  A: 

you're dividing the size of a pointer by the size of a pointer.

Marc
+9  A: 

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.

Carl Norum
"`sizeof` can only work at compile time in C"... Not exactly true in C99, since in C99 `sizeof` can be used with VLAs, in which case it works at run-time.
AndreyT
@AndreyT, good call. That doesn't apply to the dynamic-array-from-malloc approach of the OP's code though.
Carl Norum
+1  A: 

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);

N 1.1
+1  A: 

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.

John Knoeller