[英]Having trouble using Structures and Pointers in C
我正在 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
我正在尝试完成以下 function。
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]
“在非结构或联合的事物中请求成员data' in something not a structure or union" "request for member
nextPtr”
如何解决此错误并实际访问指针 *topPtr 的数据和 nextPtr? 鉴于 *topPtr 在运行时将是一个指向实际 StackNode 的指针。
topPtr
是StackNodePtr*
类型,它是StackNode**
的别名。 这意味着*topPtr
是StackNode*
类型,它是一个指针类型,您必须使用->
访问成员。
还要提防经营者.
和->
绑定比一元*
更强。 因此,您必须使用括号来操纵评估顺序:
returnable = (*topPtr)->data;
或者
returnable = (**topPtr).data;
*topPtr
给出一个StackNodePtr
。 离结构还有一层。 您需要再次取消引用它以获取 StackNode。
(**topPtr)
将给出 StackNode。
使用(**topPtr).data
或(*Ptr)->data
获取结构成员。
u r 使用了错误的语法,它应该是 topPtr->data。 此外,如果您需要学习,请立即了解 memory 泄漏。 它在你上面的程序中。 所以一旦你检索到你的数据,memory 例如。 可返回 = topPtr-> 数据; StackNodePtr *tmp = topPtr; topTracker->nextPtr = topPtr->nextPtr; 免费(tmp); 可退货;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.