Returning a pointer to a struct
-
14-04-2021 - |
Question
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?
Solution
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.
OTHER TIPS
Not in this case, since only the pointers are local, not the structs themselves, as they are passed from outside in the argument tab
.
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