【发布时间】:2019-12-20 13:55:16
【问题描述】:
我在理解 *binsearch 函数中某些代码行的机制时遇到了问题。其中,low 和 high 是两个指针,分别初始化为 &tab[0] 和 &tab[n]。在下一行中,我看到 low<high 我认为它无效,因为无法比较两个指针的两个地址。下一行也有同样的问题。不知道我说的对不对,希望大家多多指教。
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#define MAXWORD 100
int getword(char *, int);
struct key *binsearch(char *, struct key *, int);
/* count C keywords; pointer version */
main()
{
char word[MAXWORD];
struct key *p;
while (getword(word, MAXWORD) != EOF)
if (isalpha(word[0]))
if ((p=binsearch(word, keytab, NKEYS)) != NULL)
p->count++;
for (p = keytab; p < keytab + NKEYS; p++)
if (p->count > 0)
printf("%4d %s\n", p->count, p->word);
return 0;
}
/* binsearch: find word in tab[0]...tab[n-1] */
struct key *binsearch(char *word, struck 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;
}
【问题讨论】:
-
当指针指向同一个数组的元素时,比较指针是很有可能的。如果你可以将一个数字加到一个指针上得到另一个指针,那么你可以减去两个指针得到一个数字。合乎逻辑,不是吗?
-
@n.'pronouns'm。那么在这种情况下,这想显示指针在数组中的位置对吗?
-
是的。比较指针的结果和比较对应数组索引的结果是一样的。
-
NULL不等于 0。您的程序可能会因该表达式而崩溃。