返回指向结构体的指针
我在 Kernighan & 的“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;
}
看起来该函数正在返回一个指向函数中局部变量的指针;这不是返回悬空指针的情况吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不,该函数不返回指向局部变量的指针。事实上,这个函数中根本不存在
struct key
类型的局部变量。此函数返回一个指向调用者提供给此函数的
tab
数组中的struct key
元素之一的指针。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 thetab
array provided to this function by its caller.在这种情况下不是,因为只有指针是本地的,而不是结构本身,因为它们是从参数
tab
中从外部传递的。Not in this case, since only the pointers are local, not the structs themselves, as they are passed from outside in the argument
tab
.我认为您指的是
第#137页
中提到的binsearch
代码。为了更好地理解代码,您需要阅读第#138页
中给出的解释。@K&R
@C 编程语言
@第二版
I think you are referring to the
binsearch
code mentioned inpage #137
. To get better understanding of the code, you need to read the explanation given inpage #138
.@K&R
@The C Programming Language
@Second Edition