简体   繁体   English

在 C 中使用结构和指针时遇到问题

[英]Having trouble using Structures and Pointers in C

I am programming in C.我正在 C 中编程。 Considering the following Code.考虑以下代码。

My structure is defined as:我的结构定义为:

// Define the stack
struct stackNode {
char data;
struct stackNode *nextPtr;
};
typedef struct stackNode StackNode;
typedef StackNode *StackNodePtr;

The following Variables are used:使用以下变量:

StackNode topTracker; // The pointer of this stackNode will always point to the top of the stack

And I am trying to complete the following function.我正在尝试完成以下 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;

The problem is I get the following error: at Point [1] & [2] respectively问题是我收到以下错误:分别在点 [1] 和 [2]

"request for member data' in something not a structure or union" "request for member nextPtr' in something not a structure or union" “在非结构或联合的事物中请求成员data' in something not a structure or union" "request for member nextPtr”

How do I get around this error and actually access the data and nextPtr of the pointer *topPtr?如何解决此错误并实际访问指针 *topPtr 的数据和 nextPtr? Given that *topPtr will be a pointer to an actual StackNode at runtime.鉴于 *topPtr 在运行时将是一个指向实际 StackNode 的指针。

topPtr is of type StackNodePtr* which is an alias for StackNode** . topPtrStackNodePtr*类型,它是StackNode**的别名。 This means that *topPtr is of type StackNode* which is a pointer type and you must access the members using -> .这意味着*topPtrStackNode*类型,它是一个指针类型,您必须使用->访问成员。

Also beware that the operators .还要提防经营者. and -> bind stronger than unary * .->绑定比一元*更强。 You therefore have to use parenthesis to manipulate the evaluation order:因此,您必须使用括号来操纵评估顺序:

returnable = (*topPtr)->data;

or或者

returnable = (**topPtr).data;

*topPtr gives a StackNodePtr . *topPtr给出一个StackNodePtr which is still one level away from the structure.离结构还有一层。 you need to dereference it once again to get StackNode.您需要再次取消引用它以获取 StackNode。
(**topPtr) will give the StackNode. (**topPtr)将给出 StackNode。

use (**topPtr).data or (*Ptr)->data to get to the structure member.使用(**topPtr).data(*Ptr)->data获取结构成员。

u r using wrong syntax it shud be topPtr->data. u r 使用了错误的语法,它应该是 topPtr->data。 Also if u need to learn, learn now about memory leaks.此外,如果您需要学习,请立即了解 memory 泄漏。 It is there in ur above program.它在你上面的程序中。 so as soon as u retrieve ur data free the memory Eg.所以一旦你检索到你的数据,memory 例如。 returnable = topPtr->data;可返回 = topPtr-> 数据; StackNodePtr *tmp = topPtr; StackNodePtr *tmp = topPtr; topTracker->nextPtr = topPtr->nextPtr; topTracker->nextPtr = topPtr->nextPtr; free(tmp);免费(tmp); return returnable;可退货;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM