1

I have a struct named Row :

typedef struct
{
    uint32_t id;
    char username[COLUMN_USERNAME_SIZE];
    char email[COLUMN_EMAIL_SIZE];

} Row;

Also, I have defined a Macro :

#define size_of_attribute(Struct, Attribute) sizeof(((Struct *)0)->Attribute)

//  size of each attributes
const uint32_t ID_SIZE = size_of_attribute(Row, id);
const uint32_t USERNAME_SIZE = size_of_attribute(Row, username);
const uint32_t EMAIL_SIZE = size_of_attribute(Row, email);

Why are we using a null pointer while defining the size_of_attribute Macro to get the size of each data type in the struct Row? Is there any other way to express the above Macro?

2
  • 1
    Because Row is a type name, not a pointer to an instance of a Row. Commented Jun 15, 2023 at 17:02
  • 1
    There's no way to represent a struct member by itself, it has to be associated with an instance of the struct. If you don't have an existing variable to refer to, you can indirect through a pointer, and a null pointer is one that you can create on the fly like this. Commented Jun 15, 2023 at 17:08

1 Answer 1

3

Why are we using a null pointer while defining the size_of_attribute Macro to get the size of each data type in the struct Row?

Because:

  • You don't have (or need) an instance of Row
  • In sizeof expression the expression is not evaluated. It is in an "unevaluated context". Dereferencing a NULL pointer causes undefined behavior, but since this expression is not evaluated, the NULL pointer is not actually dereferenced and it's therefore safe.

Is there any other way to express the above Macro?

You could use a similar construct, pretending to actually create a Struct:

#define size_of_attribute(Struct, Attribute) (sizeof (Struct){}.Attribute)

Again, since the expression after sizeof is not evaluated, it doesn't actually create a Struct.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.