Aka*_*ash 1 c kernighan-and-ritchie
我在Kernighan&Ritchie的"C编程语言"中找到了一个返回结构的例子.
/* 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;
}
Run Code Online (Sandbox Code Playgroud)
看来该函数正在返回一个指向函数中局部变量的指针; 这不是一个返回悬空指针的情况吗?
不,此函数不返回指向局部变量的指针.事实上,struct key在这个函数中根本没有类型的局部变量.
此函数返回一个指针,指向其调用者提供给此函数struct key的tab数组中的一个元素.