[英]Why does this C code treat a local struct as a pointer, when it doesn't appear to be a pointer?
In the following code, "stk" is treated as if it is a pointer. 在下面的代码中,“ stk”被视为指针。 But after looking at it from every angle for hours, I cannot for the life of me see how it is a pointer.
但是从各个角度看了几个小时之后,我终生看不到它是一个指针。 Can someone please explain what I'm missing?
有人可以解释我所缺少的吗?
struct T {
int count;
struct elem {
void *x;
struct elem *link;
} *head;
};
T Stack_new(void) {
T stk;
NEW(stk);
stk->count = 0;
stk->head = NULL;
return stk;
}
My interpretation says that T is a struct, and therefore stk is a local, automatic variable containing a struct. 我的解释是T是一个结构,因此stk是一个包含结构的局部自动变量。 It is not a pointer, but then it gets treated as a pointer, leaving me stuck in a WTF state.
它不是指针,但是随后将其视为指针,这使我陷入了WTF状态。
More Background This code is from a book called "C Interfaces and Implementations" by Hanson. 更多背景该代码来自Hanson的一本书,名为“ C接口和实现”。 He creates a library of abstract data types that expose an interface and hide the implementation.
他创建了一个抽象数据类型库,用于暴露接口并隐藏实现。 The stack is the first one he covers.
堆栈是他覆盖的第一个堆栈。 I'm a long-time programmer just now digging into C, and apparently there's some way of parsing this syntax that I'm missing.
我是一个长期的程序员,现在正在研究C,并且显然有某种解析我所缺少的语法的方法。 Thanks.
谢谢。
In case it is relevant, here is the definition for NEW and the things that new calls: 如果相关,则这里是NEW的定义以及new调用的内容:
#define NEW(p) ((p) = ALLOC((long)sizeof *(p)))
#define ALLOC(nbytes) \
Mem_alloc((nbytes), __FILE__, __LINE__)
extern void *Mem_alloc (long nbytes,
const char *file, int line);
In the snippet above, T stk
will declare stk as a variable of type T
. 在上面的代码段中,
T stk
将stk声明为类型T
的变量。 However type T
isn't defined anywhere, and the code won't compile. 但是
T
类型没有在任何地方定义,并且代码无法编译。
If it instead said struct T stk;
如果改为说
struct T stk;
, it would be declaring stk as a variable having type struct T
. ,则将stk声明为类型
struct T
的变量。 However, the attempts to dereference stk would be meaningless and the code would again fail to compile. 但是,取消引用stk的尝试将毫无意义,并且代码将再次无法编译。
To make the example work, you could add something like, 为了使示例正常工作,您可以添加以下内容:
typedef struct T *T
which defines type T
to be a pointer to struct T
. 它定义类型
T
为pointer to struct T
的pointer to struct T
。 I would find this highly confusing though. 我会发现这很令人困惑。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.