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.

Answer from hyde on Stack Overflow
Top answer
1 of 8
18

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.

2 of 8
4

I find myself in a similar fix as you (did). I am required to packetize a given structure and knowing the exact number of bytes in the structure would help me serialize the structure. However, some structures are empty and hence, serialization fails to align exact number of bytes.

Although this is 3 years later, I found the following solution that worked for me:

Copytemplate <typename T> struct is_empty {
    struct _checker: public T { uint8_t dummy; };
    static bool const value = sizeof(_checker) == sizeof(T);
};

The result can be be queried as is_empty<T>::value and is available at compile time.

Copytemplate <typename S>
typedef union {
    struct __attribute__((__packed__)) {
        ObjId   id;
        S       obj;
    } dataStruct;
    std::array<uint8_t, (sizeof(dataStruct) - is_empty<S>::value)> byteArray;
} _msg_t;

Here are the references:

  • https://stackoverflow.com/a/4829036/1727678
  • http://www.boost.org/doc/libs/1_63_0/libs/type_traits/doc/html/boost_typetraits/reference/is_empty.html
🌐
Reddit
reddit.com › r/c_programming › i need help with checking for null in array of structure pointers
r/C_Programming on Reddit: I need help with checking for NULL in array of structure pointers
February 19, 2022 -

Hi! I started learning C a few months ago and I'm working on a simple application, it doesn't really matter.

What matters is that I'm not sure if I'm doing it alright. The application has an array of pointers to user structures, and I want this function to return a pointer to a structure that has the correct id.

I just wonder if it is required to check if the pointer isn't NULL for every pointer in the array, or is there a better way to do it?

And I know that it would be easier to read with typedefs (probably) but it's easier for me to understand what exactly I have to pass to the function :>

I also made sure for the function to return NULL if there is no user with the given id.
I tested this code and it works, I just don't know if there's a better way to do it, if it's readable or if my way of thinking is wrong/correct.

I just want to improve :3

enum UserRole {
    REGULAR,
    ADMIN,
    MASTER
};

struct User {
    enum UserRole role;
    uint64_t id;
    char* name;
    char* surname;
};

struct User *get_user_by_id(struct User* users[MAX_USERS_AMOUNT], uint64_t id)
{
    for (int i = 0; i < MAX_USERS_AMOUNT; i++) {
        if (users[i] != NULL && users[i]->id == id) {
            return users[i];
        }
    }

    return NULL;
}
Discussions

How to check whether a struct's member is NULL in C? - Stack Overflow
To expand on the above, it's important ... IN the space provided by the malloc(). The struct literally contains the int, not just a pointer to it. ... The int type is not a pointer so it can not be a NULL pointer. When you create a struct enough room is allocated for your values ... More on stackoverflow.com
🌐 stackoverflow.com
November 3, 2011
c - Checking NULL for array of structures - Stack Overflow
You can use ptr check for null if you traversing an array of pointers AND when you know that the end of such array is marked with NULL. You are not. You actually are traversing an array of structures with the ptr pointing straight to the memory location of the first element. More on stackoverflow.com
🌐 stackoverflow.com
September 20, 2013
struct pointer, check if null - C++ Forum
I am -- for practice's sake -- trying to make some sort of queue system with a simple linked list that have a queue entry structure (T value and next). I try upon adding the first element to see if there's already anyone there, but checking for a Entry* pointer existing has not proven easy ... More on cplusplus.com
🌐 cplusplus.com
c - check whether structure is null - Stack Overflow
I populated a structure(ORDER_EXPIRY_TP *OrderReqXml) and now I want to check whether structure conatains any value or not? Here is my code: OrderReqXml->fIntOrderNumbe =at_int_ord_req-> More on stackoverflow.com
🌐 stackoverflow.com
August 24, 2012
🌐
Cprogramming
cboard.cprogramming.com › c-programming › 151817-assign-null-value-struct-check-if-null.html
assign null value to a struct and check if it is null
October 30, 2012 - Just compare the members of the struct with 0. The use of memcmp may be an appropriate alternative. As I said, if you really do want to talk about a "null" struct, then you need to define precisely what that means. As yet, you have not even shown us your struct definition.
🌐
DaniWeb
daniweb.com › programming › software-development › threads › 443361 › how-to-check-a-struct-to-see-if-its-empty
How to check a struct to see if its empty? | DaniWeb
That address is never NULL, so the test is always false and your "empty" check never triggers. Instead of trying to infer emptiness by peeking at every field, design your data so you can answer the question directly. A simple pattern is to track whether a slot is used and/or keep a running count. For example, add a flag and rely on a count when listing: ... #include <stdbool.h> #define MAX_CONTACTS 3 typedef struct { char name1[15], name2[15], ph_number[15], email[25]; bool in_use; /* set true after a contact is fully added */ } contact; static contact book[MAX_CONTACTS] = {0}; /* zero-initialize so in_use starts false */ static size_t used = 0; /* how many contacts are actually stored */
🌐
Cplusplus
cplusplus.com › forum › beginner › 47704
struct pointer, check if null - C++ Forum
When you call add() the first time, last is NULL, so your if statement allocates front, but you didn't assign a value to it.
🌐
DaniWeb
daniweb.com › programming › software-development › threads › 314197 › null-check-a-struct-member
c++ - Null check a struct member [SOLVED] | DaniWeb
A robust pattern is to zero-initialize the struct and always guard C library calls: ErrorInformation info = {0}; /* all pointers NULL, arrays zeroed */ /* or: ErrorInformation *p = calloc(1, sizeof *p); */ if (info.TestName && info.TestName[0] != '\0') { /* non-empty string */ } /* Safe length computation */ size_t name_len = info.TestName ?
Find elsewhere
Top answer
1 of 3
3

In your code, the initialization

Outer_t outer_instance = {
   {NULL},
   {
    0,
    1,
    2,
    3,
    table_defined_somewhere_else,
   }
};

is invalid. You are trying to assign NULL to Outer_t.tableA which is of non-pointer type Inner_t. NULL can only be assigned to pointers.

Most C compilers define NULL as 0 or ((void*)0). Depending on your compiler, this syntax may be allowed but will be expanded to 0, effectively setting all fields in the first Inner_t structure to zero. In any case, this code will not do what I think you believe it will.

Your notion of tableA being undefined or non-existent is wrong. As your structures are currently defined, declaring an object of type Outer_t will automatically create two Inner_t objects as structure members (and those Inner_t structures will automatically create the objects they are composed of, etc). If outer_instance exists, then outer_instance.tableA and outer_instance.tableB are guaranteed to exist. They cannot be "undefined" (they are defined when you defined the Outer_t data type) or "NULL" (has no meaning except for pointers). A structure which has members defined is never "empty".

Now, it is a valid concern whether or not tableA or tableB have been initialized. There is no universally-appropriate way to do this. One method is to fill the entire structure with some pre-defined value when it is declared, and to check for the presence of that value as a sign that the structure has not been initialized. This assumes, however, that there is a value that you should never see as valid data within that structure; many times, such a value does not exist.

If you want to build your code in such a way that the members of Outer_t may or may not exist, then you should use pointers (such as Inner_t* tableA) as members of Outer_t instead of structures. That way, you can NULL the pointer to indicate a non-existent table. However, you would not be able to declare the contents of the inner structs at the same time as the outer struct in the manner which you currently do.

Edit: Looking at your updated code, it appears that you are getting that particular error because you are trying to assign an object of type Items_t to a field of type Items_t*. Use &items_instance here and your error should go away (provided that items_instance is defined before outer_instance, and all elements of items_instance can be determined at compile time).

2 of 3
0

In the revised code, you're setting the first field of outer_instance to NULL, but trying to set the second field to items_instance directly. Since the field has type Items_t* but items_instance has type Items_t, you're getting a type error.

You want to set the field to the address of items_instance, so use &items_instance.

🌐
Quora
quora.com › How-do-I-check-if-a-pointer-is-null-in-C
How to check if a pointer is null in C - Quora
Answer (1 of 5): From the top: #ifndef NULL #define NULL (*)(0) #endif /**********************************/ /* we just have set a value for a */ /* NULL pointer. From ancient times */ /* this points to physical and or */ /* logical address 0 *************/ /******************************...
🌐
Stack Overflow
stackoverflow.com › questions › 37069428 › check-pointer-in-struct-is-null › 37069571
c - Check pointer in struct is NULL - Stack Overflow
May 6, 2016 - zone* z = malloc(sizeof(zone)); z->cases = malloc(sizeof(Case)*300); for(i = 0; i < 300; i++) { Case* c = z->cases[i]; if(c->fourmilier) // HERE IS RAISE SEGMENTATION FAULT { if(read( &nbTypeFourmib, sizeof( unsigned char))==-1) { exit(EXIT_FAILURE); } } } ... typedef struct { unsigned short foodSpawnfreq; unsigned short foodUnit; unsigned char sourceFood; Case** cases; TypeFourmi** TypeFourmi; TypeFourmi** TypeBibibte; } zone; typedef struct{ fourmiliere* fourmilier; bibite* bibit; fourmis* fourmi; char obstacle; } Case;
🌐
W3Schools
w3schools.com › c › c_null.php
C NULL
For example, fopen() returns NULL if a file cannot be opened, and malloc() returns NULL if memory allocation fails. We can check for this using an if statement, and print an error message if something goes wrong.
🌐
Unreal Engine
forums.unrealengine.com › development › programming & scripting › blueprint
How to check if struct is empty? - Blueprint - Epic Developer Community Forums
April 27, 2020 - So I know for Blueprint Objects we’ve got the isValid function, but for a struct this function doesn’t exist. How do I check if a struct is empty?
🌐
Quora
quora.com › In-the-C-language-is-it-true-that-a-struct-itself-as-opposed-to-the-individual-items-comprising-the-struct-cannot-be-assigned-to-NULL-If-so-why
In the C language, is it true that a struct itself - as opposed to the individual items comprising the struct - cannot be assigned to NULL? If so, why? - Quora
Answer (1 of 7): A struct is a composite type, consisting of one actual size in bytes, that can be broken down into individual typed components. As such, it can be assigned in whole only by either giving it a list of initial values at its first definition, or assigning it to another struct of th...
Top answer
1 of 2
2

You may only compare a pointer to NULL. An Adjustment itself will never be NULL.

2 of 2
2

In C++, a "reference" denoted by & implies that the caller of your method is obligated to provide you with an object instance. There is no (NORMAL) way to call your method without an object. You are free to assume that you if your function is called, the aAdjustement will be set to something.

However, there are two gothas here:

(1) It will be set to something, but will that 'something' be meaningful? Is a Adjustement structure completely zeroed-out a valid value for your function? If not - then you may test that instead test nulliness. If any structure value combinations are invalid - use this as the discriminator. If all possible values are valid - then there's nothing to be checked.

(2) If you know the dark ways (tm), you actually CAN PASS a null-reference to this function. So your code is not "safe from nulls" just because "you used reference&". However, as I said, with use of & you clearly state that you disallow nulls. A caller that knows the dark ways(tm) may only blame himself when your function crashes.

disclaimer: "normal" and "the dark ways" are just buzzwords to hide extra complexity of a real professional explanation. If you play a bit with casting and */& operators, you will quickly discover how to get i.e. "int& boom" that would point to a zero-address. This is not so "dark" nor "magic", it's plain feature of the language and platform. However, (A) novice programmers and even somewhat experienced programmers tend to not know that references can be null, and (B) the convention of &-means-dont-pass-null is really well known and settled, so (A+B) please adapt to the convention and feel free to use it where adequate.

🌐
Wikihow
wikihow.com › computers and electronics › software › programming › c programming languages › how to check null in c: 7 steps (with pictures) - wikihow
How to Check Null in C: 7 Steps (with Pictures) - wikiHow
June 9, 2025 - The main disadvantage to the PTR == NULL method is the chance that you'll accidentally type ptr = NULL instead, assigning the NULL value to that pointer. This can cause a major headache.