直接从 typedef 结构定义创建指针

Creating a pointer directly from a typedef struct definition

我想检查以下代码的含义。我想我正在创建一个指向 adjlistnode 结构指针列表的指针,但我不确定。

代码如下:

typedef struct adjlistnode {int node; int cost; struct adjlistnode *next;}
    **AdjMatrix;

我对 **AdjMatrix 到底是什么感到困惑。就像我上面说的,我认为它是指向指向 adjlistnode 结构的指针列表的指针,但我不确定。我的假设是否正确?

I think it is a pointer to a list of pointers to adjlistnode structures

不,不是。

AdjMatrix 成为表示 a pointer to pointer to struct adjlistnode

的类型

例如,它可以像这样使用:

AdjMatrix p = NULL; // p is now a pointer to pointer to struct adjlistnode

代码好像是建立链表的,AdjMatrix好像是指向头指针的指针的简写。它可以像这样使用:

void addNode(AdjMatrix pHead, int node, int cost)
{
    struct adjlistnode *tmp = malloc(sizeof *tmp);
    tmp->node = node;
    tmp->cost = cost;
    tmp->next = *pHead;
    *pHead = tmp;
}

void deleteNode(AdjMatrix pHead)
{
    if (*pHead)
    {
        struct adjlistnode *tmp = *pHead;
        *pHead = tmp->next;
        free(tmp);
    }
}

int main(void) {
    struct adjlistnode *head = NULL;

    // Add nodes
    addNode(&head, 1, 2);
    addNode(&head, 3, 4);
    addNode(&head, 5, 6);

    // ... use the list

    // Delete nodes
    while(head) deleteNode(&head);

    return 0;
}

请注意,typedef 的指针通常被认为是不好的做法。相反,最好这样做:

typedef struct adjlistnode {int node; int cost; struct adjlistnode *next;} AdjMatrix;

并像这样使用它:

void addNode(AdjMatrix **pHead, int node, int cost)

明确表示 pHead 是指向 AdjMatrix

的指针

围绕 typedef 的规则可以简化为以下概括:如果您在 C 中有任何有效的变量声明(没有存储 class,例如 externstaticregister, 等等), 然后在前面加上一个 typedef 将变量名变成一个新的类型名, 基于变量的类型.

所以在这里,没有 typedef:

struct adjlistnode {int node; int cost; struct adjlistnode *next;}
    **AdjMatrix;

AdjMatrix 是指向 struct adjlistnode.

指针类型的变量

但是在你的 post 中,由于 typedefAdjMatrix 是指向 类型 指针的名称 18=].

来自 typedef [强调已添加]:

typedef is a reserved keyword in the C and C++ programming languages. It is used to create an alias name for another data type. 1 As such, it is often used to simplify the syntax of declaring complex data structures consisting of struct and union types, but is just as common in providing specific descriptive type names for integer data types of varying lengths.

AdjMatrixstruct adjlistnode **类型的替代名称,是指向struct adjlistnode的指针。

您可以使用它来声明这样的变量:

AdjMatrix pp_st_adjlistnode;

表示pp_st_adjlistnode是指向struct adjlistnode的指针。