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
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.

Discussions

C++ return null struct from function - Stack Overflow
It makes no sense for a struct instance to be null. This isn't Java where most everything is a reference to an object. ... Give AUTO a way to represent a "no-value". For example by making weight -1. Or by adding a flag to it. This is pretty ugly; I don't recommend it, even though it's somewhat common in practice. Return a (smart) pointer instead of ... More on stackoverflow.com
🌐 stackoverflow.com
C++: Return NULL instead of struct
I have a struct Foo. In pseudocode: def FindFoo: foo = results of search foundFoo = true if a valid foo has been found return foo if foundFoo else someErrorCode How can I accomplish th... More on stackoverflow.com
🌐 stackoverflow.com
function cannot return null in c - Stack Overflow
Stack push(Stack stk,int data) ... stk.count++; return stk; } Here is the error I'm getting: error: returning 'void *' from a function with incompatible result type 'Stack' (aka 'struct Stack') return NULL; I'm not sure what this means. How do I fix it? What is the NULL equivalent of a Stack? ... There is no equivalent. ... Your function and approach have to be redesigned. For example return bool instead, which will ... More on stackoverflow.com
🌐 stackoverflow.com
c - Unable to return NULL in a function that expects an integer return type - Stack Overflow
Stack Overflow for Teams is now ... layer of enterprise AI. Read more > Find centralized, trusted content and collaborate around the technologies you use most. Learn more about Collectives ... Connect and share knowledge within a single location that is structured and easy to search. Learn more about Teams ... I am trying to return NULL in my fucntion, ... More on stackoverflow.com
🌐 stackoverflow.com
🌐
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
}
🌐
Cprogramming
cboard.cprogramming.com › c-programming › 92776-null-struct.html
NULL struct
August 18, 2007 - student *a; if(a==NULL){ printf("NULL"); } I was trying to see if that struct node is empty or not.I was expecting 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 value, and therefore point somewhat randomly to any variable.
🌐
SEI CERT
wiki.sei.cmu.edu › confluence › display › c › MSC19-C.+For+functions+that+return+an+array,+prefer+returning+an+empty+array+over+a+null+value
MSC19-C. For functions that return an array, prefer returning an empty array over a null value - SEI CERT C Coding Standard - Confluence
In this case, the calling code need not change—iterating over the elements works correctly even if the returned array is empty, so the calling code need not check the return value for NULL. This situation is complicated by the fact that C does not keep track of the length of an array. However, two popular methods have emerged to emulate this behavior. The first is to wrap the array in a struct with an integer storing the length.
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.
🌐
Bytes
bytes.com › home › forum › topic › c sharp
how can i return null when returning a struct - Post.Byes
October 31, 2015 - Re: how can i return null when ... 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....
🌐
DaniWeb
daniweb.com › programming › software-development › threads › 422892 › struct-empty-value
c++ - struct empty value | DaniWeb
struct Contact { std::string name; int id = 0; // default ctor generated; members have sane defaults }; If you need heap semantics or polymorphism, prefer smart pointers over raw new/delete: return std::unique_ptr<Contact> and return nullptr on failure.
🌐
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
🌐
Stack Overflow
stackoverflow.com › questions › 36244088 › passing-a-struct-pointer-containing-null-all-of-a-sudden-contains-a-struct-inste
c - Passing a struct pointer containing NULL all of a sudden contains a struct instead of NULL - Stack Overflow
#include "Header.h" #include <stdio.h> #include <stdlib.h> void two(List *self) { //*self does not = NULL now //*self = a struct with null data and next values } void one(List *self) { two(&self); // *self = 0x0000... NULL } int main() { List test = NULL; one(&test); } ... I don't think this will be allowed *ThePointer with struct definition . ... Sorry I cant show the actual code as it's an assignment.: We can't help you this way.
🌐
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...
🌐
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]...
🌐
Buzzphp
buzzphp.com › posts › c-return-null-instead-of-struct
C++: Return NULL instead of struct - Buzzphp
December 1, 2021 - I have a struct Foo. In pseudocode: def FindFoo: foo = results of search foundFoo = true if a valid foo has been found return foo if foundFoo else someErrorCode ... Edited to remove numerous inaccuracies. C++ objects can never be null or empty.