sizeof typedef pointer

瘦欲@ 提交于 2019-12-08 07:02:57

问题


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.



来源:https://stackoverflow.com/questions/43304880/sizeof-typedef-pointer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!