我正在用 C 撰寫一個程式,它有一個容器(線性鏈表),其中包含 char 陣列作為其資料。我需要撰寫一個函式 firstItem(container* containerADT) 回傳結構變數 top。我已經嘗試以多種不同的方式多次撰寫 firstItem 函式,但我總是遇到同樣的錯誤。我的結構定義、函式和錯誤訊息如下:
容器和節點結構:
typedef struct node
{
char* data;
struct node *next;
}node;
typedef struct container
{
struct node *top;
}container;
第一項功能:
node* firstItem(container* containerADT)
{
// returns the top of the passed container
return containerADT->top;
}
測驗功能
printf("\nTesting firstItem() on a non-empty container:");
node *firstItem;
firstItem = firstItem(container1);
numTestsCompleted ;
if (firstItem != NULL && strcmp(firstItem->data, "item 1") == 0)
{
printf("\n\tSUCCESS! firstItem() returned the first item in the container.\n");
}
else
{
printf("\n\tFailed. firstItem() did not return the first item in the container.\n");
numTestsFailed ;
}
錯誤資訊:

請注意,我被要求測驗 firstItem() 函式,所以我不能只訪問容器的頂級變數,并且 Makefile 用于編譯 main.c、container.c 和 container.h
uj5u.com熱心網友回復:
問題是您已將變數命名為與函式相同的名稱。然后該變數在區域范圍內“隱藏”函式的定義。
node* firstItem = firstItem(container1);
重命名變數以使用另一個名稱:
node *first_item = firstItem(container1);
if (first_item != NULL && strcmp(first_item->data, "item 1") == 0) {
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/537264.html
標籤:C指针函数指针
上一篇:投射匿名二維陣列
下一篇:傳遞對抽象類物件的參考
