简体   繁体   中英

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.

The create_family(int generations) function is returning a person* or in other words a pointer, * , to a 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 *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';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM