gpt4 book ai didi

c - 指针有问题吗?

转载 作者:行者123 更新时间:2023-12-01 12:04:12 26 4
gpt4 key购买 nike

我在理解 *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;
}

最佳答案

如果两个指针属于同一数组,则可以比较它们。

特别是这些是您可以使用或不使用指针执行的操作:

  • Pointer comparison is Valid only if the two pointers are Pointing to same array.

  • All Relational Operators can be used for comparing pointers of same type.

  • All Equality and Inequality Operators can be used with all Pointer types.

  • Pointers cannot be Divided or Multiplied.



所以 low < high在这种情况下是允许的并且运行良好。

关于c - 指针有问题吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59426404/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com