英文:
Do we need to add * when typedefining with one already
问题
当编写这个C结构时:
typedef struct node_s* node_t;
struct node_s {
int value;
node_t next;
};
每当我们定义一个类型为 node_t
的变量时,我们不需要添加一个指针 *
吗?
例如:
node_t f(node_t node) {
...
}
这样,f
接收一个节点并返回一个节点。
英文:
When writing this C struct:
typedef struct node_s* node_t;
struct node_s {
int value;
node_t next;
};
Anytime we define a variable of type node_t
we don't need to add a pointer *
?
For example:
node_t f(node_t node) {
...
}
such that f
receives a node and returns one.
答案1
得分: 1
node_t
是对 struct node_s *
的别名,所以
node_t p;
等价于
struct node_s *p;
和
node_t f( node_t node )
等价于
struct node_s *f( struct node_s *node )
说了这些之后...
一般来说...
在typedef背后隐藏指针不是一个好主意,除非你还提供了一个API,从用户那里隐藏了类型的“指针性”。
如果你的类型的用户必须显式地对其进行解引用或访问成员以正确使用它,那么不要隐藏指针或结构的特性在typedef背后。
英文:
node_t
is an alias for struct node_s *
, so
node_t p;
is exactly equivalent to
struct node_s *p;
and
node_t f( node_t node )
is exactly equivalent to
struct node_s *f( struct node_s *node )
Having said all that...
It's generally not a good idea to hide a pointer behind a typedef unless you also provide an API that hides the "pointer-ness" of the type from the user.
If the user of your type has to explicitly dereference it or access a member in order to use it properly, then don't hide the pointer-ness or the struct-ness behind a typedef.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论