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

标签 c pointers struct

我正在用 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/

相关文章:

c - 我的代码不起作用。我的 while 循环有问题

c++ - 调用从不兼容类型转换而来的零数据结构的成员函数 - 未定义?

c - 从 C 语言的电话簿代码的文本文件中读取信息

c - TASK_UNINTERRUPTIBLE 和使用 C 在 linux 内核开发中处理线程

ios - 链接器错误 - 尝试链接到 arm,但链接器使用 x86

c - 定义为 double 和 int 的函数的输出

c++ - 使用 "->"调用函数

pointers - 当值指向另一个实例时,go 的 big.Int 基础值会发生变化

我们可以在 C 语言中将整数值转换为指针类型吗?

C# 使用数组编码(marshal)结构