2013-05-04 45 views
0

我有一個函數sortbyName,它返回一個遞歸數據結構sortedListsortList本身包含一個指向另一個遞歸數據結構stud_type的指針,它們全部定義如下。爲C中的遞歸數據結構定義變量C

typedef struct stud_type_ { 
    int matricnum;     
    char name[20];   

    struct stud_type_ *next_student; 
} stud_type; 

typedef struct sort_List { 
    stud_type *cur; 
    struct sortList *next; 
} sortList; 

stud_type listofStudents; // Assume that it is not NULL 

sortList * sortbyName() { 
    sortList *sList; 

    //sort algorithm here 
    return sList; 
} 
... 
... 

int main() { 
//trying to define curTEST = sortbyName() here 
    while (curTEST!=NULL) { 
     printf("Name: %s\n", curTEST->cur->name); 
     curTEST = curTEST->next; 
    } 
} 

現在我想在main()函數變量賦值從我sortbyName功能保存返回值,所以我可以用while循環遍歷它,並打印出結果。那麼我如何定義這個變量?我試過sortList curTEST;sortList * curTEST;無濟於事。或者我的sortbyName函數的定義有問題嗎?

編輯: 我試着編譯它並糾正最瑣碎和不那麼瑣碎的錯誤/警告,直到它來到這個電流誤差報告,其中並沒有什麼太大的意義了我。

u2_4.c:208:15: warning: implicit declaration of function 'sortbyName' is invalid in C99 
     [-Wimplicit-function-declaration] 
    curTEST = sortbyName(); 
      ^
u2_4.c:208:13: warning: incompatible integer to pointer conversion assigning to 'sortList *' 
    (aka 'struct sort_List *') from 'int' [-Wint-conversion] 
    curTEST = sortbyName(); 
      ^~~~~~~~~~~~~~~~~~~ 
2 warnings generated. 
Undefined symbols for architecture x86_64: 
    "_sortbyName", referenced from: 
     _main in u2_4-Szd3la.o 
ld: symbol(s) not found for architecture x86_64 
clang: error: linker command failed with exit code 1 (use -v to see invocation) 
make: *** [u2_4] Error 1 

在我main功能,我定義curTEST這樣的:sortList * curTEST;

+1

再次讀取您的類型名稱。 'sortList * curTest = ...'。並且在'struct sort_List * next;'的定義中,您需要正確拼寫'struct'標籤。 – 2013-05-04 12:23:48

+0

'sortedList' - >不應該是'sortList'嗎? – stijn 2013-05-04 12:24:00

+0

'sortList *'not'sortedList *' – suspectus 2013-05-04 12:25:23

回答

1

你定義你的函數在不同的文件,或者......在定義的main()?如果它在其他地方被定義,並且在main()之前沒有函數原型,那麼您將得到警告和鏈接器錯誤。

我在單個文件(main.c)中完成了以下所有操作,並且它沒有任何問題編譯。

typedef struct stud_type_ { 
    int matricnum; 
    char name[20]; 

    struct stud_type_ *next_student; 
} stud_type; 

typedef struct sort_List { 
    stud_type *cur; 
    struct sort_List *next; 
} sortList; 

stud_type listofStudents; // Assume that it is not NULL 

sortList * sortbyName() { 
    sortList *sList; 

    //sort algorithm here 
    return sList; 
} 

int main() { 
    sortList * curTEST = sortbyName(); 

    while (curTEST!=NULL) { 
     printf("Name: %s\n", curTEST->cur->name); 
     curTEST = curTEST->next; 
    } 
    return 0; 
} 

請注意,我只對您的文件做了兩處更改。定義指向next的指針時,我更改了sortList的結構。我把它從struct sortList *next改爲struct sort_List *next。我定義並初始化curTEST爲sortList * curTEST = sortbyName()

+0

是啊,謝謝,我想我得到它的工作..至少這個問題的解決。我之前在另一個文件中定義了它,但沒有函數原型。 – mercurial 2013-05-05 12:15:40