我正在用 C 语言编程。 考虑以下代码。
我的结构定义为:
// Define the stack
struct stackNode {
char data;
struct stackNode *nextPtr;
};
typedef struct stackNode StackNode;
typedef StackNode *StackNodePtr;
使用以下变量:
StackNode topTracker; // The pointer of this stackNode will always point to the top of the stack
我正在尝试完成以下功能。
char pop( StackNodePtr *topPtr ){
char returnable;
// store the Node.data from the top of the stack
returnable = *topPtr.data; //[1]
// Set the next Node to the top of the stack
topTracker.nextPtr = *topPtr.nextPtr; //[2]
// return the Node data.
return returnable;
问题是我收到以下错误:分别在点 [1] 和 [2]
“请求非结构或 union 中的成员数据””
“请求非结构或 union 中的成员
nextPtr'”
如何解决此错误并实际访问指针 *topPtr 的数据和 nextPtr?假定 *topPtr 在运行时将是指向实际 StackNode 的指针。
最佳答案
topPtr
的类型为 StackNodePtr*
,它是 StackNode**
的别名。这意味着 *topPtr
的类型为 StackNode*
,这是一种指针类型,您必须使用 ->
访问成员。
还要注意运算符 .
和 ->
的绑定(bind)比一元 *
更强。因此,您必须使用括号来操纵计算顺序:
returnable = (*topPtr)->data;
或
returnable = (**topPtr).data;
关于c - 在 C 中使用结构体和指针时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6160958/