c - 获取成员请求不是结构或 union 错误

标签 c pointers struct stack

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

struct stackNode 
{
  char data;
  struct stackNode *nextPtr;
};

typedef struct stackNode StackNode; 
typedef StackNode *StackNodePtr;

当我尝试将它用于我的 pop 方法时,我收到了许多错误消息。我的 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 必须是 StackNodePtr

谁能帮我解决这个问题?

最佳答案

您的 topPtr 是指向结构的指针 (StackNodePtr *topPtr = struct stackNode **topPtr)。所以你应该写 (*topPtr) -> data 而不是 topPtr -> data

事实上,行 char c = topPtr->data; 也应该导致错误。

关于c - 获取成员请求不是结构或 union 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16464390/

相关文章:

c - 如果指针只是地址,为什么我不能将特定的 int 地址分配给指针?

c - 从动态结构数组中删除元素时出现未定义的行为

c - 如何使用结构将指针值从单独的函数传递回 main

c - 使用存储在其结构中的变量访问数组元素

c - 计算 C 中结构的大小(数据对齐问题)

c - 打印字符数组时 Valgrind 读取大小为 8 的内容无效

c - 前向声明结构体的范围

c++ - 错误 C2440 : '='  : cannot convert from 'char *(__cdecl *)(int,int)' to en 'GetItemText_t'

c++ - 如何通过在 Arduino 中引用我的类来传递串行对象?

c - 难以理解 C 中双指针的值