请耐心等待,我是其他语言的新手,从 http://c.learncodethehardway.org/book/learn-c-the-hard-way.html 学习 c 语言
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;
}
我理解第二个 Person_create 函数返回一个 struct Person 的指针。我不明白的是(可能是因为我来自其他语言,erlang,ruby),为什么它定义为
struct Person *Person_create(char *name, int age, int height, int weight)
不是
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)
{
struct Person who;
who.name = strdup(name);
who.age = age;
who.height = height;
who.weight = weight;
return who;
}
但并不经常使用。
关于c - 定义一个返回结构指针的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10452103/