[英]Questions about functions that return pointers
I'm trying to understand some of the distribution code我正在尝试了解一些分发代码
typedef struct person
{
struct person *parents[2];
char alleles[2];
}
person;
person *create_family(int generations);
int main(void)
{
person *p = create_family(GENERATIONS);
}
Why do we have to put the star operator inside of our prototype.为什么我们必须将星号运算符放在我们的原型中。 Is it always necessary to include the star operator inside of prototypes?
是否总是需要在原型中包含星号运算符?
@Barmar has already pointed this out in the comments: the *
is not a operator applied to a function prototype, it is instead referring to a pointer return type. @Barmar 已经在评论中指出了这一点:
*
不是应用于 function 原型的运算符,而是指指针返回类型。
The create_family(int generations)
function is returning a person*
or in other words a pointer, *
, to a struct person
. create_family(int generations)
function 将person*
或换句话说*
指针返回到struct person
。
You could also write it like this:你也可以这样写:
person* create_family(int generations);
Or like this:或者像这样:
person * create_family(int generations);
This is similar to declaring a pointer variable to a person
struct, the *
is part of the type declaration of the variable.这类似于向
person
结构声明指针变量, *
是变量类型声明的一部分。
person *johnDoe = NULL;
On the other hand, the *
symbol in, a different context, is also used as the dereference operator.另一方面,不同上下文中的
*
符号也用作解引用运算符。 This is the same symbol, but completely different meaning, operator instead of part of a type declaration.这是相同的符号,但含义完全不同,运算符而不是类型声明的一部分。
(*johnDoe).alleles[0] = 'G';
(*johnDoe).alleles[1] = 'T';
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.