Search code examples
c++cdata-structures

How to check if a struct is NULL in C or C++


i have the following structure

typedef struct 
{
   char      data1[10];
   char      data2[10];
   AnotherStruct  stData;
}MyData;

for some reason the implementors choose not to make the stData as pointer, so i have to live with that. my problem is how do i check if the stData member is empty? because if it is empty i need to skip certain things in my code.

any help is appreciated


Solution

  • You need some way to mark AnotherStruct stData empty.

    • First check (or double-check) the documentation and comments related to AnotherStruct, possibly ask those who made it if they are available, to find out if there is an official way to do what you want.

    • Perhaps that struct has a pointer, and if it is null pointer, the struct is empty. Or perhaps there is an integer field where 0 or -1 or something can mean empty. Or even a boolean field to mark it empty.

    • If there aren't any of the above, perhaps you can add such a field, or such an interpretation of some field.

    • If above fails, add a boolean field to MyData to tell if stData is empty.

    • You can also interpret some values (like, empty string? Full of 0xFF byte?) of data1 and/or data2 meaning empty stData.

    • If you can't modify or reinterpret contents of either struct, then you could put empty and non-empty items in different containers (array, list, whatever you have). If MyData items are allocated from heap one-by-one, then this is essentially same as having a free list.

    • Variation of above, if you have empty and non-empty items all mixed up in one container, then you could have another container with pointers or indexes to the the non-empty items (or to the empty items, or whatever fits your need). This has the extra complication, that you need to keep two containers in sync, which may or may not be trivial.