c - 定义一个返回结构指针的函数

标签 c

请耐心等待,我是其他语言的新手,从 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/

相关文章:

c - 奇怪的 printf 和 scanf 行为

c - 将分配的值存储到分配的数组

c - 在函数中使用二维数组返回指向数字出现次数最多的行的指针

c - 释放结构数组

C指针char到小写

android ion, ION_IOC_IMPORT 的 ioctl 返回 <0, errno = 9

c - 如何在 C 中打印到标准输出和文件

CC3200 RTOS 多线程

c - 将文件放在哪里以便 C 程序可以访问它们?

c - 通过 POSIX tdelete() 访问节点数据