我正在查看以下代码(取自Learn C the Hard Way)并且我对开始的函数的代码感到困惑:
struct Person *Person_create(char *name, int age, int height, int weight)
据我所知,“struct Person”告诉C该函数将返回该类型的结构;我也理解该函数采用字符指针和3个整数作为参数。然而,令我困惑的是,函数的名称以“*”开头。我认为* Person_create只是函数的名称所以我不明白它为什么需要星号。
#include <stdio.h>
#include <assert.h>
#include <stdlib.h>
#include <string.h>
struct Person {
char *name;
int age;
int height;
int weight;
};
struct Person *Person_create(char *name, int age, int height, int weight)
{
struct Person *who = malloc(sizeof(struct Person));
assert(who != NULL);
who->name = strdup(name);
who->age = age;
who->height = height;
who->weight = weight;
return who;
}
void Person_destroy(struct Person *who)
{
assert(who != NULL);
free(who->name);
free(who);
}
void Person_print(struct Person *who)
{
printf("Name: %s\n", who->name);
printf("\tAge: %d\n", who->age);
printf("\tHeight: %d\n", who->height);
printf("\tWeight: %d\n", who->weight);
}
int main(int argc, char *argv[])
{
// make two people structures
struct Person *joe = Person_create(
"Joe Alex", 32, 64, 140);
struct Person *frank = Person_create(
"Frank Blank", 20, 72, 180);
// print them out and where they are in memory
printf("Joe is at memory location %p:\n", joe);
Person_print(joe);
printf("Frank is at memory location %p:\n", frank);
Person_print(frank);
// make everyone age 20 years and print them again
joe->age += 20;
joe->height -= 2;
joe->weight += 40;
Person_print(joe);
frank->age += 20;
frank->weight += 20;
Person_print(frank);
// destroy them both so we clean up
Person_destroy(joe);
Person_destroy(frank);
return 0;
}
答案 0 :(得分:3)
空间与*
无关struct Person *Person_create
与
相同struct Person* Person_create
该函数返回指向结构Person
的指针作为旁听,我通常会保留*和&amp;与类型,因为你说的是指向struct Person&#34;的&#34;指针的类型。但其他人喜欢在名称和*之间加一个空格。
答案 1 :(得分:1)
这意味着该功能不会返回struct Person
,它会将指针返回给struct Person
。
答案 2 :(得分:0)
此签名:
struct Person *Person_create(char *name, int age, int height, int weight)
告诉你返回值的类型是指向struct Person的指针。该函数的名称不以星号开头。
相反,返回struct Person
的函数的签名如下所示:
struct Person Person_create(char *name, int age, int height, int weight)
一般情况下(也很短),在大多数情况下返回指针比返回整个结构更经济(因为它需要更少的空间和时间来将指针作为返回值传递)。这可能是为什么应该回馈结构的C函数通常会返回指向它的指针的主要原因。
答案 3 :(得分:0)
正如其他人所说,*是返回类型的一部分。您需要返回一个指针而不是结构本身,因为该结构只存在于函数堆栈内存中。一旦函数返回,您将无法再访问它,它将是垃圾。 应该以这种方式返回原语和指针。
如果你坚持要返回一个struct,那么需要使用函数内的malloc将它分配给堆。稍后,如果您首先引用它,则可以使用free来回收此内存。这样做的问题是要记住哪些结构被分配而哪些结构没有被分配。在释放结构时,这将是一种非常容易的方法,难以追踪分段错误。
一般来说,你应该返回指针和原语,因为其他任何东西都可能很大且成本很高。根据您的cpu架构,指针的大小与int几乎相同。
如果您正在使用struct *,请记住使用 - &gt;代替 。到达它的属性。