繁体   English   中英

传递到在C函数指针结构即使提前声明不工作

[英]Struct pointer passed into function in C does not work even after forward declaration

我是C语言的新手,正在学习链接列表。 我在Linux Mint上使用GCC编译器使用Code Blocks IDE。 我试图将结构指针传递给可以帮助我遍历链接列表的函数。 这是我目前的代码:

#include <stdio.h>
#include <stdlib.h>

void gothru(struct node * Root);

struct node {
    int data; //data in current node
    struct node * next; //pointer to the next node
};

void gothru(struct node * Root){
    struct node * conductor; //this pointer will be used to traverse the linked list
    conductor = Root; //conductor will start at the Node

    /* Conductor traverses through the linked list */
    if(conductor != NULL){
        while(conductor->next != NULL){
            printf("%d->",conductor->data);
            conductor = conductor->next; /*if current position of conductor is not pointing to
                                           end of linked list, then go to the next node */
        }
        printf("%d->",conductor->data);
    }

    printf("\n");

    if (conductor == NULL){
        printf("Out of memory!");
    }

    free(conductor);
}

int main()
{
    struct node * root; //first node

    root = malloc(sizeof(*root)); //allocate some memory to the root node

    root->next = NULL; //set the next node of root to a null/dummy pointer
    root->data = 12; //data at first node (root) is 12

    gothru(root); //traverse linked list


    return 0;
}

现在,我已经以与首次初始化该函数时完全相同的格式在顶部声明了我的函数。 但仍然出现以下错误:

| 11 |错误:“ gothru”的类型冲突

我尝试将“ gothru”函数的参数更改为简单变量,在这种情况下它可以工作。 但是当我回到指向该结构的指针的那一刻,它给了我这个错误。

Stackoverflow中的先前答案表示,我们需要向前声明我们的函数以清除此错误。 我确实做到了,但是仍然行不通。 有什么办法吗?

gothru函数的前向声明包含结构类型作为参数之一,因此,您需要在结构定义之后移动gothru的前向声明。

否则,函数参数(类型)在前向声明时间内未知。

就像是

struct node {
    int data; //data in current node
    struct node * next; //pointer to the next node
};

void gothru(struct node * Root);  // struct node is known to compiler now

应该解决问题。

使用GCC我们得到这个,如果我们试图编译代码:

vagrant@dev-box:~/tests$ gcc test.c
test.c:4:20: warning: ‘struct node’ declared inside parameter list [enabled by default]
 void gothru(struct node * Root);
                    ^
test.c:4:20: warning: its scope is only this definition or declaration, which is probably not what you want [enabled by default]
test.c:11:6: error: conflicting types for ‘gothru’
 void gothru(struct node * Root){
      ^
test.c:4:6: note: previous declaration of ‘gothru’ was here
 void gothru(struct node * Root);
      ^

这是第一个显示的警告是理解这到底是怎么回事至关重要。 在这里, struct node首先在函数原型内声明,其作用范围就是这一行。 但是它声明了功能。 现在,在定义struct node您会遇到函数定义,但是在这一行中, struct node含义与第一个原型中遇到的本地struct node有所不同。 这就是为什么你得到一个冲突的类型的功能。

正如@SouravGhosh的答案所指出的那样,该解决方案就是将结构定义移到函数原型之前。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM