if( mystruct == NULL )

mystruct is not a pointer, so you cannot compare it with NULL.

You have three options:

  1. Add a status field to MyStruct to indicate whether the struct has been initialized correctly.
  2. Allocate the struct on the heap and return it by pointer.
  3. Pass the structure as a pointer argument and return a status code (thanks @Potatoswatter).
Answer from NPE on Stack Overflow
๐ŸŒ
Cprogramming
cboard.cprogramming.com โ€บ c-programming โ€บ 92776-null-struct.html
NULL struct
August 18, 2007 - student *a; if(a==NULL){ ... it to return NULL because struct has no data.where am i go wrong? How to find if a struct is empty / null ? thanks ... All you're doing is making a new pointer to a student variable. When you declare a variable like that and you don't initialize it, then it could contain any ...
Discussions

How can I return a struct from a function?
Nothing special about it. struct foo { int i; }; struct foo bar() { struct foo s = { 1 }; return s; } More on reddit.com
๐ŸŒ r/C_Programming
45
29
December 25, 2023
C++ return null struct from function - Stack Overflow
You would have to engineer some ... that can be tested (see boost::optional for example.) ... There are many options: return a pointer (and nullptr is a valid return), throw an exception, return a bool and return the value via a reference parameter, have a "sentinel" value indicating a non-valid AUTO... ... @KeithThompson I am looking for good duplicates. There are plenty out there, but so far I have only found ones with poor answers. ... It makes no sense for a struct instance to ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
function cannot return null in c - Stack Overflow
Connect and share knowledge within a single location that is structured and easy to search. Learn more about Teams ... My code is supposed to push a StackNode item into a Stack. However, when the stack is full, I'm trying to get the function to not push anymore, and return a null, but it won't ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
c - Why is my struct pointer creating function returning NULL because of a local declaration? - Stack Overflow
I've decided to go through all of D&R's exercises and in doing so I have encountered a peculiar event. Based on the book's own addtree function I modified it for my own structure: struct gnode ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
Top answer
1 of 6
68

There are several practical reasons why functions like fopen return pointers to instead of instances of struct types:

  1. You want to hide the representation of the struct type from the user;
  2. You're allocating an object dynamically;
  3. You're referring to a single instance of an object via multiple references;

In the case of types like FILE *, it's because you don't want to expose details of the type's representation to the user - a FILE * object serves as an opaque handle, and you just pass that handle to various I/O routines (and while FILE is often implemented as a struct type, it doesn't have to be).

So, you can expose an incomplete struct type in a header somewhere:

typedef struct __some_internal_stream_implementation FILE;

While you cannot declare an instance of an incomplete type, you can declare a pointer to it. So I can create a FILE * and assign to it through fopen, freopen, etc., but I can't directly manipulate the object it points to.

It's also likely that the fopen function is allocating a FILE object dynamically, using malloc or similar. In that case, it makes sense to return a pointer.

Finally, it's possible you're storing some kind of state in a struct object, and you need to make that state available in several different places. If you returned instances of the struct type, those instances would be separate objects in memory from each other, and would eventually get out of sync. By returning a pointer to a single object, everyone's referring to the same object.

2 of 6
40

There are two ways of "returning a structure." You can return a copy of the data, or you can return a reference (pointer) to it. It's generally preferred to return (and pass around in general) a pointer, for a couple of reasons.

First, copying a structure takes a lot more CPU time than copying a pointer. If this is something your code does frequently, it can cause a noticeable performance difference.

Second, no matter how many times you copy a pointer around, it's still pointing to the same structure in memory. All modifications to it will be reflected on the same structure. But if you copy the structure itself, and then make a modification, the change only shows up on that copy. Any code that holds a different copy won't see the change. Sometimes, very rarely, this is what you want, but most of the time it's not, and it can cause bugs if you get it wrong.

๐ŸŒ
DaniWeb
daniweb.com โ€บ programming โ€บ software-development โ€บ threads โ€บ 422892 โ€บ struct-empty-value
c++ - struct empty value | DaniWeb
You can't return null unless you are returning a pointer from a function. But if you don't want to use pointers there are a couple of options.
๐ŸŒ
Reddit
reddit.com โ€บ r/c_programming โ€บ how can i return a struct from a function?
r/C_Programming on Reddit: How can I return a struct from a function?
December 25, 2023 -

Hello,

I am a c beginner and just thought id try writing a basic compiler.

I want to assign a struct in a function because it allows me to allocate memory much more efficiently based on the size of each element.

My code takes in a line and performs some tokenization on it and verifies syntax.

Example syntax: (I have a seperate function to remove spaces)

int(abc) = (1+a+b+Cdedf)

I want to return the entire struct in the end of the function or return NULL if something went wrong.

char varAssignment(char *line) //Lexers int/float/str declaration    //CODE WORKS - JUST NEED TO PASS CHAR AND RETURN STRUCT
{

    //Memory assignment
    char lineCopy[strlen(line)];
    strcpy(lineCopy,line);

    strtok(lineCopy,"(");
    int variableMemSize = strlen(strtok(NULL,")"));
    strtok(NULL,"(");
    int varListMemSize = strlen(strtok(NULL,")"));



    struct varStruct //Struct assignment
    {
        char datatype[4];
        char variable[variableMemSize+1];

        char varList[varListMemSize+1];
    };



    struct varStruct varStructx;


    strncpy(varStructx.datatype,strtok(line,"("),4); // Get int/flt/str prefix


    if ((strcmp(varStructx.datatype,"int") != 0 && strcmp(varStructx.datatype,"flt") != 0 && strcmp(varStructx.datatype,"str")) != 0) //Did not declare int/flt/str correctly
    {
        printf("Datatype ERROR | Cannot accept '%s'",varStructx.datatype); //Incorrect datatype
        return NULL;
    }

    strcpy(varStructx.variable,strtok(NULL,")")); //Get variable name


    if (strcmp(strtok(NULL,"("),"=") != 0) //Did not put '='
    {
        printf("Syntax ERROR | Expected '%c' in assignment",'=');
        return NULL;
    }


    strcpy(varStructx.varList,strtok(NULL,")")); //Get variable list


    return varStructx; //WANT TO RETURN THIS STRUCT
}
๐ŸŒ
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...
Find elsewhere
๐ŸŒ
Quora
quora.com โ€บ Is-it-legal-in-C-C-to-return-NULL
Is it legal in C/C++ to 'return NULL'? - Quora
Answer (1 of 21): There is no such thing like โ€œC/C++โ€. return NULL is legal in C and it usually means, by convention, that something went wrong, e.g. an allocation, and the calling context is supposed to handle the error.
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 72995012 โ€บ why-is-my-struct-pointer-creating-function-returning-null-because-of-a-local-dec
c - Why is my struct pointer creating function returning NULL because of a local declaration? - Stack Overflow
when the tree is empty, the line in the original code struct gnode *p = (struct gnode *)malloc(sizeof(struct gnode)); allocates a new gnode object, but also defines a new identifier p with a local scope, effectively shadowing the argument name. Hence the argument variable p is not updated and ultimately the original value (a null pointer) is returned by return p; at the end of the function.
๐ŸŒ
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;
}
๐ŸŒ
Bytes
bytes.com โ€บ home โ€บ forum โ€บ topic โ€บ c sharp
how can i return null when returning a struct - Post.Byes
October 31, 2015 - You would have to do something like return an object type instead and have the caller unbox, have a special return struct value meaning "null" or return as a ref param and have an error code as the return of the function.
๐ŸŒ
Unity
forum.unity.com โ€บ unity engine
How return null into a function that return a specific type ? - Unity Engine - Unity Discussions
July 28, 2015 - Hi guys, I have a List that contains instances of a custom struct : public struct MovieItem{ public string name; public MovieTexture movieTexture; } public List movies; Then I have a function that tries to retrieve a MovieItem based on the name property - if the MovieItem is found out then it is returned - if not I return null : public MovieItem GetMovieItemByName(string movieName){ for (int i=0; i
๐ŸŒ
Quora
quora.com โ€บ Can-you-return-null-in-C
Can you return null in C++? - Quora
Answer (1 of 10): If you are interfacing with C and dealing with pointers you can return a pointer to an object. That pointer can be NULL, if the function fails or actually succeeds but returns a null value. Because NULL is universally represented as a pointer to address [code ]0x00000000[/code]...
๐ŸŒ
W3Schools
w3schools.com โ€บ c โ€บ c_null.php
C NULL
It helps you avoid using pointers that are empty or invalid. You can compare a pointer to NULL to check if it is safe to use. Many C functions return NULL when something goes wrong. For example, fopen() returns NULL if a file cannot be opened, and malloc() returns NULL if memory allocation fails.