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