0

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?

2
  • Your function has no return statement. This will likely trigger an illegal instruction error if it even compiles. Commented Sep 8, 2019 at 2:47
  • 1
    char * slice2(const char * str, const size_t * start, const size_t * end) { size_t begin = (start == NULL ? 0 : *start); return (end == NULL ? strdup(str + begin) : strndup(str + begin, *end - begin)); } godbolt.org/z/DUINJi Commented Sep 8, 2019 at 3:02

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

thanks for this. It's very helpful for understanding what I'm trying to do.
Additionally, why can't I do something like if (end == NULL) *end = string_len; ? That will raise a Segmentation Fault (if I don't declare it a constant to start with).
@Shared If end is NULL then *end tries to dereference a NULL pointer. Do you understand why that is a problem?
@Blastfurnace -- I see, so in that case, I'd want to do something like -- inferred_end = (end != NULL) ? *end : string_len;, right?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.