我正在尝试实现堆栈。我有以下堆栈结构:

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

如果我把temp设为StackNode(并调整->为)。因此,我得到错误"request for member ‘nextPtr’ or ’data’ in something not a structure or union"。在给我的问题中,topPtr必须是aStackNodePtr
有人能帮我解决这个问题吗?

最佳答案

您的topPtr是指向结构的指针(StackNodePtr *topPtr=struct stackNode **topPtr)。所以你应该写(*topPtr) -> data而不是topPtr -> data
实际上,行char c = topPtr->data;也会导致错误。

09-15 21:15