简体   繁体   中英

Dereferencing pointer type when in sizeof()

I have following structure:

typedef struct _foo_t {
    int bar;
    float buzz;
    char quux[40];
} *const foo_t;

Is there a way to get the size of structure, like it's done via sizeof(struct _foo_t) , but using only name foo_t ? I have tried sizeof(*foo_t) , but that does not compile.

I don't believe you can do this directly. You'll need to define an intermediate typedef if you want to do this:

typedef struct _foo_t {
    int bar;
    float buzz;
    char quux[40];
} foo_t;

typedef foo_t *const foo_tp;

// sizeof(foo_t) should work

Dereferencing a type doesn't really make sense in C. You can dereference a variable, but not a type. In C++, you can do these kinds of type operations using templates, but that's not really applicable since you indicate the C tag.

You could also declare a dummy variable of the appropriate type to invoke sizeof on an expression:

foo_tp f;
// sizeof(*f) should work

你可以通过使用这样的复合文字来完成这个:

sizeof(*(foo_t){NULL})

foo_t is a typedef , so it is like a type.

*foo_t is not a valid expression, because you cannot dereference a type.

Since it is not a valid expression, you cannot get its size.

It is as writing:

typedef int * pointer_to_int_type;

size_t a = sizeof(*pointer_to_int_type);

You cannot use a type name as an operand (not only for sizeof), as an expression requires to have a type (in C, types are no first class citizens like in full OO-languages like Python). However, you can use a type-name alone when using the parenthesized version - C11 draft 6.5.3.4#1/2. An understandable restriction.

Note that an expression in parenthesis after the sizeof keyword would have different gramatical semantics: the parenthesis are part of the expression, while for a type name, they are part of the sizeof operator (which would work like a function call). (I'm really not keen writing a parser for C myself.)

I for myself do normally not typedef pointers. That hides the semantics and supports forgetting about their somewhat special (and dangerous) properties. An exception would be an external interface where the pointer is externally used more like a handle than a pointer. But this I really only use at the outer membrane.

Ok, as I got from the discussion, you are trying to work with opaque pointers. But that will not work by defining the struct type and the pointer at once anyway. You will need to split that:

"hidden_stuff.h":

typedef struct HiddenStruct * const HiddenStructHandle;

"hidden_stuff.c"

#include "hidden_stuff.h"

struct HiddenStruct {
    ...
};

Having the struct in the header will break the encapsulation/hiding.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM