指向类型定义结构的指针

Pointer to a type-defined structure

好的,我有一个以前编写的代码。这是我正在做的作业,我无法更改这些代码行:

typedef struct
{
    int number;
    float average;

} B_PLAYER;


typedef struct
{
    char n[20];
    B_PLAYER k[12];

} TEAM;

还有两个声明的函数,如下所示:

int result (TEAM t1, TEAM t2); 

↑ exclude this function for now, this calculates the result of a match

TEAM* createTeam();

我必须编写的代码应该模拟一场篮球比赛(总共 32 支球队的多场比赛)。因为作业太长(而且有点复杂),所以我会尽量简短。所以上面代码的第一部分定义了名为 B_PLAYER 和 TEAM 的类型,这是我理解的。但我的问题是,为什么类型名称 TEAM 用作函数 return 类型以及指向该类型名称的指针是什么意思(do):

TEAM* createTeam(); <------------ 这个

请记住,此函数需要创建一个篮球队的地址和 return 相同的地址。它必须从 main() 函数(标准输入)中读取值。必须填写所有 12 个位置和所有套件编号。

我很乐意收到一些反馈。如果您需要更多信息,我会写下整个作业。 :)

TEAM* createTeam(); 声明一个函数,该函数 returns 指向分配在别处的 TEAM 结构变量的指针。意思是里面的某个地方可能有这样的代码:

TEAM* t = malloc(sizeof *t);
...
return t;

附带说明一下,空括号在 C 中是过时的样式。您应该写成 TEAM* createTeam(void).

But my question is, why is the type name TEAM used as a function return type and what does the pointer to that type name mean(do):

TEAM* createTeam(); <------------ This

你读错了。 TEAM 是用作函数return类型!

TEAM* 应该被理解为“一件事”——你不能分成两部分,比如 TEAM 有一个意思,而 * 有另一个意思。它必须读作 TEAM*,这意味着 指向 TEAM 对象的指针

因此 TEAM* createTeam(); 意味着您必须 return 指向 TEAM 对象的指针的值。简而言之,我们只是说:“return 一个指向 TEAM 对象的指针”只是因为它隐含在 C 中,始终运行 return 值。

So how can you get a TEAM object and return a pointer to it inside a function?

答案是malloc(和朋友)。喜欢:

TEAM* createTeam()
{
    TEAM* team_ptr;                       // Create a pointer to a TEAM object
    team_ptr = malloc(sizeof *team_ptr);  // Allocate memory for a TEAM object and
                                          // assign the address of that memory
                                          // to the pointer
    if (team_ptr == NULL) exit(1);        // Error checking
    return team_ptr;                      // Return (the value of) the pointer to the TEAM object
}

例如main 你可以这样做:

TEAM* teamA = createTeam();
TEAM* teamB = createTeam();

现在您有 2 个指向不同 TEAM 对象的指针。

但是等等……它们没有价值。不,您需要添加一些代码来读取要分配给 TEAM 对象的值。可能是这样的:

TEAM* createTeam()
{
    TEAM* team_ptr;
    team_ptr = malloc(sizeof *team_ptr);
    if (team_ptr == NULL) exit(1);

    // Read team name
    fgets(team_ptr->n, sizeof team_ptr->n, stdin);
    size_t len = strlen(team_ptr->n);
    if (len > 0) team_ptr->n[len-1] = '[=12=]';  // remove newline if present

    // Read the players
    for (int i = 0; i < 12; ++i)
    {
        team_ptr->k[i].number = 42;    // Add your own code to get it from stdin
        team_ptr->k[i].average = 42.0; // Add your own code to get it from stdin
    }
    return team_ptr;
}

提示:fgets 和 sscanf 可能对“缺失”代码有用。

所以现在您可以在例如main :

TEAM* teamA = createTeam();
TEAM* teamB = createTeam();
printf("Next match will be %s playing %s\n", teamA->n, teamB->n);
printf("Player number %d at team %s has average %f\n", teamA->k[0].number, teamA->n, teamA->k[0].average);

一旦你完成了你的团队:

free(teamA);
free(teamB);