How to check if an initialised struct is empty or not?

30,379

Solution 1

Just make sure you initialise the pointer to NULL:

text* t = NULL;

then later you can malloc on demand, e.g.:

if (t == NULL)
{
    t = malloc(sizeof *t);
    // NB: check for error here - malloc can fail!
}
t->head = foo;

Solution 2

Simply initialize the pointer whan it is defined

text* t = NULL;

In this case you can check whether an object that should be pointed to by the pointer was allocated

if ( t != NULL ) { /* some action */ }

or you can write

if ( t && t->head ) { /* some action */ }

Take into account that if a pointer is defined outside any function that is if it has the static storage duration then it initialized implicitly by the compiler to a null pointer constant.

Share:
30,379
user3484582
Author by

user3484582

Updated on May 25, 2020

Comments

  • user3484582
    user3484582 almost 4 years

    So I want to check if my struct is empty or not. I declare my struct as a variable but DO not allocate memory.

    text* t;

    Later on I want to check with an if statement whether my struct is empty or not. if (t!=NULL) does not seem to work as t has an address. Also doing something like if (t->head != NULL) gives me a segfault as I haven't allocated any memory for the struct.

    I don't want to malloc as soon as I declare t. Is there a way to check if my struct is empty?

    Thanks in advance!