Alex Rivera | Logout

define a function returning struct pointer

Asked 2012-05-04T15:50:00.303
12

Please bear with me, i m from other language and newbie to c and learning it from http://c.learncodethehardway.org/book/learn-c-the-hard-way.html

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;
}

I understand the second Person_create function returns a pointer of struct Person. I don't understand is(may be because i m from other language, erlang, ruby), why does it define it as

struct Person *Person_create(char *name, int age, int height, int weight)

not

struct Person Person_create(char *name, int age, int height, int weight)

and is there other way to define a function to return a structure?

sorry if this question is too basic.

c
Edit
Report

1 Answer

13

It is defined so because it returns a pointer to a struct, not a struct. You assign the return value to a struct Person *, not to struct Person.

It is possible to return a full struct, like that:

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;
}

But it is not used very often.

answered 2012-05-04T15:52:22.767

Your Answer