首页 文章

链表:指针的类型“next”和struct的名称是否相同?

提问于
浏览
0
#include<stdio.h>
#include<stdlib.h>
typedef struct {
    int val;
    struct node* next;
} Node, *NodePtr;
void makeInitialLinkedList(int a[], int n)
{
    int i;
    NodePtr rec=NULL;
    NodePtr head=NULL;
    for (i=0; i<n; i++) {
        NodePtr cur=(NodePtr)malloc(sizeof(Node));
        if (i==0) head=cur;
        if (rec!=NULL) rec->next=(node*)cur;
        cur->val=a[i];
        cur->next=NULL;
        rec=cur;
    }

    // test
    while(n--) {
        printf("%d ", head->val);
        head=(NodePtr)head->next;
    }
}
NodePtr copy(NodePtr head)
{
    return NULL;
}
int main()
{
    //Mission #2
    int initialDataArray[10]={5,3,2,8,9,7,0,6,4,1};
    makeInitialLinkedList(initialDataArray, 10);

}

我不明白为什么会这样 . 我最初没有为结构命名,只是通过typedef创建了一个姓氏“Node” . 那么“struct node * next”如何正常工作? node *是一种数据类型,如int *或char *?我这样想:

typedef struct strName {
    int val;
    struct strName* next;
} strSurName, *strPtr;

指针“next”的类型和struct的初始名称是否相同?

2 回答

  • 0

    使用 struct node* next 作为您的(未命名)结构的成员,您实际上做了两件事 - 向前声明结构 struct node 并将名为 next 的成员定义为指向(向前声明的) struct node 的指针 . 请注意, struct node ,因为它只是向前声明,是不完整的,并且是一个额外的新结构,它与您实际想要引用的封闭结构不同 . 同意struct forward declaration at cppreference

    以下形式结构名称的声明;隐藏标记名称空间中名称名称的任何先前声明的含义,并将名称声明为当前作用域中的新结构名称,稍后将对其进行定义 . 在定义出现之前,此结构名称具有不完整的类型 . 这允许相互引用的结构:

    struct y;
    struct x { struct y *p; /* ... */ };
    struct y { struct x *q; /* ... */ };
    

    所以看起来好像你有一个指向你正在定义的相同 struct 的指针,但实际上你是(向前声明)并使用一个新结构 . 请参阅以下示例,该示例实际编译 .

    struct known_struct {
        int a[20];
    };
    
    struct own_struct {
        int val;
        struct known_struct* known;
        struct own_struct *own;
        struct unknown_struct* unknown;
    } test;
    
    int main(){
    
        size_t sizeOfKnownMember = sizeof(*(test.known));  // gives 80
        size_t sizeOfMemberOwn = sizeof(*(test.own));  // gives 32
        // size_t sizeOfunknownMember = sizeof(*(test.unknown));  // invalid application of sizeof to incomplete type `struct unknown_struct`
    
        return 0;
    }
    
  • 2

    我不明白为什么会这样 .

    它没有,你应该得到编译错误,像gcc 6.3或4.2.1这样:

    prog.c: In function ‘makeInitialLinkedList’:
    prog.c:15:35: error: ‘node’ undeclared (first use in this function)
             if (rec!=NULL) rec->next=(node*)cur;
                                       ^~~~
    prog.c:15:35: note: each undeclared identifier is reported only once for each function it appears in
    prog.c:15:40: error: expected expression before ‘)’ token
             if (rec!=NULL) rec->next=(node*)cur;
                                            ^
    

    Deduplicator的现场演示 .

    node *是一种数据类型,如int *或char *?

    不会 . 除非你自己定义 node ,否则你所拥有的将导致错误 .

    指针的类型“next”和struct的初始名称是否相同?

    这就是主意 .

相关问题