我想實現一個堆棧。我有以下的堆棧結構:獲取成員的請求不是結構或聯合錯誤
struct stackNode
{
char data;
struct stackNode *nextPtr;
};
typedef struct stackNode StackNode;
typedef StackNode *StackNodePtr;
當我嘗試使用此爲我的pop方法,我得到了一些錯誤信息。我的流行方法是:
char pop(StackNodePtr *topPtr)
{
if (IsEmpty(topPtr))
{
printf("Can't pop element from stack: stack is empty.\n");
return 'n'; // arbitrary char to end if, will adjust this later.
}
char c = topPtr->data; //save data to be returned
// temporary StructNodePtr to save data
StackNodePtr temp; // temporary StackNodePtr
temp = malloc(sizeof(StackNodePtr));
temp->data = topPtr->data; //line 52, first error
temp->nextPtr = topPtr->nextPtr;
//replace values in topPtr, this section I have yet to debug, is likely faulty.
topPtr->data = temp->nextPtr->data; //line 56, third error
topPtr->nextPtr = temp->nextPtr;
free(temp);
return (c);
}
我收到以下錯誤信息:
52:22: error: request for member ‘data’ in something not a structure or union
53:25: error: request for member ‘nextPtr’ in something not a structure or union
56:10: error: request for member ‘data’ in something not a structure or union
57:10: error: request for member ‘nextPtr’ in something not a structure or union
如果我做一個溫度StackNode(和調整 - >相應地),我得到的錯誤"request for member ‘nextPtr’ or ’data’ in something not a structure or union"
。在給我的問題中,topPtr
必須是我的StackNodePtr
。
有人可以幫我解決這個問題嗎?
首選解決方案:仔細閱讀整個程序,非常小心地注意指向結構體和結構體的指針,以及如何使用每個結構體,以及如何像對待第一個那樣修復您處理的位置。例如,'topPtr-> data'對於'topPtr'來說實在是一個指向StackNode的指針,但它不是......它是一個指向指針的指針。 '* topPtr-> data'會得到你要找的東西。 – mah 2013-05-09 14:43:58
你的'malloc'最有可能也是錯的。你應該做'temp = malloc(sizeof(StackNode));'通常認爲隱藏指針在'typedef'中通常被認爲是不好的做法。你容易混淆間接程度。 – 2013-05-09 15:49:49