2017-09-12 6 views
1

私はC言語を新しくしており、リンクリストを学習しています。私はGCCコンパイラでLinux MintのCode Blocks IDEを使用しています。私は、リンクされたリストをトラバースするのに役立つ関数への構造体ポインタを渡そうとしています。ここに私の現在のコードは次のとおりです:Cの関数に渡された構造体ポインタは、前方宣言の後でも機能しません

#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; 
} 

私は、機能が最初に初期化された時と全く同じ形式で先頭に私の関数を宣言しました。私はそれが働く場合には、単純な変数への私の「gothru」関数の引数を変更しようとしている

|11|error: conflicting types for ‘gothru’

:しかし、まだ、私は次のエラーを取得しています。しかし、私が構造体へのポインタに戻ると、このエラーが出ます。

私は、このエラーをクリアするために関数を宣言する必要があると言います。私はそれを正確に行いましたが、それでも動作しません。どんな解決策ですか?

答えて

4

gothru関数の前方宣言には、構造体の型がパラメータの1つとして含まれているため、構造定義の後に前方宣言を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を使用して

+2

の場合はすぐに提供されるため、提供する必要はありません。 –

+0

さて、ちょうどこれをしました。出来た!ありがとう! – ragzputin

+0

@ Jean-FrançoisFabre正解ですが、害はありません。 :) –

1

我々はこれを取得:最初に示されている

[email protected]:~/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の回答によって既に指摘されています。すなわち、関数プロトタイプの前に構造体定義を移動することです。

関連する問題