簡體   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