user11954200
user11954200

Reputation:

How to print/detect a null value in C

I have the following function where I'm trying to pass a NULL to emulate an "optional" parameter:

char * slice2(const char * str, const unsigned int * start, const unsigned int * end) {

    size_t string_len = strlen(str);

    printf("Start: %d | End: %d\n", *start, *end);

    if (*start == NULL) inferred_start = 0;
    if (*end == NULL) inferred_end = string_len;

    // more code and such
} 

And called as:

unsigned int start = 6;
printf("'%s' ==> %s\n", "String", slice2("String", &start, NULL));

What would be the proper way to do the above?

Upvotes: 0

Views: 230

Answers (1)

Keith Thompson
Keith Thompson

Reputation: 263267

start is a pointer to an unsigned int, so *start is an unsigned int, an integer.

Your test if (*start == NULL) is trying to compare an integer value to a null pointer constant.

Unfortunately, it could compile without error, because NULL can legally be defined simply as 0. But to test whether start is a null pointer, use

if (start == NULL) ...

and likewise for end.

Also, this line:

printf("Start: %d | End: %d\n", *start, *end);

should be executed only after you've confirmed that neither start nor end is a null pointer.

Upvotes: 1

Related Questions