1

I came across a example returning a struct in 'C Programming Language' by Kernighan & Ritchie.

/* binsearch: find word in tab[0]...tab[n-1] */
struct key *binsearch(char *word, struct key *tab, int n)
{
    int cond;
    struct key *low = &tab[0];
    struct key *high = &tab[n];
    struct key *mid;

    while (low < high) {
        mid = low + (high-low) / 2;
        if ((cond = strcmp(word, mid->word)) < 0)
            high = mid;
        else if (cond > 0)
            low = mid + 1;
        else
            return mid;
    }

    return NULL;
}

It seems that the function is returning a pointer to a local var in the function; wouldn't this be a case of returning a dangling pointer?

Deduplicator
  • 44,692
  • 7
  • 66
  • 118
Akash
  • 4,956
  • 11
  • 42
  • 70

3 Answers3

7

No, this function does not return a pointer to a local variable. There are, in fact, no local variables of type struct key in this function at all.

This function returns a pointer to one of the struct key elements from the tab array provided to this function by its caller.

James McNellis
  • 348,265
  • 75
  • 913
  • 977
1

Not in this case, since only the pointers are local, not the structs themselves, as they are passed from outside in the argument tab.

MByD
  • 135,866
  • 28
  • 264
  • 277
1

I think you are referring to the binsearch code mentioned in page #137. To get better understanding of the code, you need to read the explanation given in page #138.

@K&R

@The C Programming Language

@Second Edition

Sangeeth Saravanaraj
  • 16,027
  • 21
  • 69
  • 98