c - 返回指针的函数声明

标签 c pointers

这是我的代码:

#include <stdio.h>

struct entry
{
    int value;
    struct entry *next;
};

struct entry * findEntry (struct entry *listPtr, int match)
{
    while (listPtr != (struct entry *) 0)
        if (listPtr->value == match)
            return (listPtr);
        else
            listPtr = listPtr->next;

    return (struct entry *) 0;
}

int main(void)
{
    struct entry * findEntry(struct entry * listPtr, int match);
    struct entry n1, n2, n3;
    struct entry * listPtr, *listStart = &n1;

    int search;

    n1.value = 100;
    n1.next  = &n2;

    n2.value = 200;
    n2.next  = &n3;

    n3.value = 100;
    n3.next  =   0;

    printf("Enter value to locate: ");
    scanf ("%i", &search);

    listPtr = findEntry (listStart, search);

    if (listPtr != (struct entry *) 0)
        printf( "Found %i.\n", listPtr->value);
    else
        printf("Not found.\n");

    return 0;
}

所以对于这一行:

struct entry *findEntry (struct entry *listPtr, int match) 

为什么查找条目前面有一个*?因为它应该是一个函数声明,但 *findEntry 是一个指针?我根本不明白这句话是什么......

书中的解释是:指定函数 findEntry() 返回一个指向条目结构的指针,并且它将这样的指针作为其第一个参数,将整数作为第二个参数

在这种情况下需要 * 符号吗?

谢谢

最佳答案

假设有人告诉您 23+45 等于 275,然后通过以下逻辑进行解释:我们必须计算 3+4 > 分开,保持两边的25不变即可。这当然是没有意义的。 23+45 表示法的正确含义并不意味着应该将 3+4 部分剥离出来并单独对待。

当您将 *findEntry 与声明的其余部分隔离开来并断定它将 findEntry 声明为指针时,您实际上会犯同样的错误。您的声明中没有 *findEntry 这样的实体。声明语法规定右侧的 (...) 位首先绑定(bind)到名称 findEntry。只有在那之后我们才开始考虑名称左侧的 *

这意味着您的 findEntry 声明以 findEntry(...) 绑定(bind)开头,这表明 findEntry 是一个函数。只有在此之后我们才考虑 * 位,获得 *findEntry(...),它告诉我们 findEntry 是一个返回的函数一个指针。

关于c - 返回指针的函数声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40334937/

相关文章:

c++ - 使用指针将字节数组转换为无符号整数

c# - 在 C# 中使用数组和指针与 C DLL

python - 在 cython 类中包装一个预初始化的指针

c++ - 在 c 中的二维数组的末尾添加一个额外的数据列

c++ - 为什么芯片控制语言选择

C 到汇编,每条指令翻译器

c++ - 为什么函数指针定义可以使用任意数量的与号 '&' 或星号 '*' ?

c/c++ flock 在 linux 上作为互斥体对文件删除不稳健

C++:用于识别原始指针使用情况的统计信息

c - strcat 生成崩溃程序 (0xc0000005)