sizeof typedef pointer

2019-05-31 22:31发布

问题:

I have a struct that defined like that:

typedef struct my_struct
{
    int numbers[10];
}
*my_struct;

Is there a way to find out its size?

sizeof(my_struct);// return size of a pointer

回答1:

The struct type itself is spelled with struct, so you can say:

sizeof (struct my_struct)

This would not work if you hadn't also given your struct a name, which would have been possible:

typedef struct { int numbers[10]; } * foo;  /* struct type has no name */
foo p = malloc(1000);
p->numbers[3] = 81;

I'd say all of this is poor code that is needlessly terse for no reason. I would just keep all the names unique, and name everything, and not alias pointers, for that matter. For example:

typedef struct my_struct_s my_struct;

my_struct * create_my_struct(void);
void destroy_my_struct(my_struct * p);

struct my_struct_s
{
    int numbers[10];
};

Everything has a unique name, the typedef is separate from the struct definition, and pointers are explicit.