在 C 中带有指针的 typedef [英] typedef with pointer in C
问题描述
我是 C 编程的初学者,正在研究链表.我正在尝试创建一个链接列表,它将以正确的顺序显示字母.该程序使用户能够按字母顺序在列表中插入一个字符或从列表中删除一个字符.所以,我在某种程度上遵循了一个例子,但有一些我无法理解的东西.
I am beginner in C programming and I am studying on Linked Lists. I am trying to create a Linked List which is gonna display the letters in correct order. The program enables the user to insert a character in the list in alphabetical order or to delete a character from the list. So, I follow an example to a point but there is something that I cannot understand.
这是代码的第一部分:
#include <stdio.h>
#include <stdlib.h>
struct listNode {
char data;
struct listNode *nextPtr;
};
typedef struct listNode ListNode;
typedef ListNode *ListNodePtr;
在那部分之后,程序从函数原型开始.我知道底部第二行中 typedef
的用法.但我不知道的是,代码的最后一行包含:
After that part, program starts with the function prototype.
I know the usage of typedef
in the second line from the bottom.
But what I don't know is, the last line of the code which contains:
typedef ListNode *ListNodePtr;
这是什么意思?
推荐答案
简短版本:
typedef ListNode *ListNodePtr;
将 ListeNodePtr
定义为 ListNode 的指针.
您可能想知道为什么星号在这里粘"在 ListNodePtr
上.这是因为在 C 声明中,指针被视为类型修饰符,因此在声明中,它是 declarator(变量的标识符或 typedef
类型).(*) 只要你在一行中有多个声明,这就是相关的,例如以下内容:
You may wonder why the asterisk is "sticking" to ListNodePtr
here. That's because in C declarations, being a pointer is considered a type modifier, so in a declaration, it's part of the declarator (the identifier of the variable or typedef
'd type).(*) This is relevant as soon as you have multiple declarations in a single line, e.g. the following:
int *a, b;
将定义一个指向 int a
的指针和一个普通的 int b
.
would define a pointer to int a
and a plain int b
.
你可以把它写成
int* a, b;
但这会非常令人困惑,因为 b
仍然不是是一个指针.
but that would be very confusing, because b
would still not be a pointer.
说了这么多,我个人认为typedef
一个指针是糟糕的风格,因为作为一个C程序员,你知道的含义一个星号.将它隐藏在 typedef
后面(就像这里所做的那样,用一些非标准后缀如Ptr"替换它)只会让其他人更难阅读代码.
All that being said, I personally consider it bad style to typedef
a pointer, because as a C programmer, you know the meaning of an asterisk. Hiding it behind a typedef
(and as done here, replacing it by some non-standard suffix like "Ptr") just makes the code harder to read for others.
(*) 在这里添加了脚注:这种设计背后的原因是声明应该与用法相同.*a
取消引用一个指针,所以 *a
也应该声明一个指针.
(*) added footnote here: the reasoning behind this design is that declarations should look the same as usage. *a
dereferences a pointer, so *a
should as well declare a pointer.
这篇关于在 C 中带有指针的 typedef的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!