0

I want to check if a defined struct has been initialized So i thaught of using

typedef struct
{
    int *isInitialized;
} Thing;

int main()
{
    Thing a;
    //Only if initialized, should always fail now
    if (a.isInitialized == NULL)
    {
        //Code
    }
    //I'm saying a is initialized
    a.isInitialized = NULL;
}

Will this work or is there any (even small) chance the pointer will automatically be assigned to NULL when declaring a?

EDIT: I know it is not always NULL. I'm asking if it is ever NULL or will it always be some random not-NULL pointer

Alex Sim
  • 403
  • 3
  • 16

2 Answers2

0

Will this work or is there any (even small) chance the pointer will automatically be assigned to NULL when declaring a?

No, you can't do that. There is no guarantee that an uninitialised pointer is always NULL.

Similar to int, there is no guarantee that an initialised int is 0.

int a;
if(a == 0)  // should always be zero
{
   // code
}
else  // a must be initialised? wrong
artm
  • 17,291
  • 6
  • 38
  • 54
0

If the pointer variable is declared as local, well, there is a chance that the pointer will have the value identical to NULL. The immediate problems are 1) when this occurs is pretty much random and 2) compiler will complain that you are accessing uninitialized variable.

On the other hand, if the pointer is declared as global and uninitialized, it is guaranteed that its content is initialized to zero, which, in almost all practical cases, corresponds to NULL.

Yogi Jason
  • 121
  • 5