TakShing
TakShing

Reputation: 145

Unable to return NULL in a function that expects an integer return type

Warning: return makes integer from pointer without a cast [enabled by default] return NULL;

I am trying to return NULL in my fucntion, but it's not working out and I don't understand why it is so. Below is my code, but I will not post the entire thing since I am only having problems with the return statement. I hope you can understand.

#include<stdio.h>
#include<stdlib.h>
#include<math.h>

typedef struct {
 int* data;
 unsigned int len;
} intarr_t;

int intarr_save_binary( intarr_t* ia, const char* filename )
{
    if(ia == NULL)
    {
        return NULL; // problem here, I want to return NULL if intarr_t*ia is null
    }
    else
    {
     // remaining code here, but is uncessary
     return 0;
     }
 }

My final question is also how do I check if the char array filename is NULL?

Would I do this:

if (filename == NULL)
{
     return NULL;
}

Upvotes: 3

Views: 16261

Answers (3)

zeynep
zeynep

Reputation: 1

try

int? intarr_save_binary( intarr_t* ia, const char* filename )

Upvotes: 0

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385104

It looks like you've misunderstood what NULL means in C. Types are not nullable. NULL is effectively just a shorthand for the pointer with value 0! And int is not a pointer.

Upvotes: 2

yellowantphil
yellowantphil

Reputation: 1493

If the return type is int, you can't return a NULL. To show an error, you could instead return a special value like zero or -1, if you check for that value in any calling function. Lots of functions return nonnegative numbers on success, or -1 on error.

NULL cannot be stored in an int variable, unlike in SQL, for example. If you ignore the warning and return NULL anyway, then NULL will be casted to zero. The calling function won't be able to tell whether you returned NULL or zero.

If your function only needs to indicate success or failure, then it's common to return 1 for success, and zero for failure. Zero means "false" when treated as a boolean value (like in if statements), and non-zero means "true."

Upvotes: 4

Related Questions