将变量设置为函数的返回类型

时间:2011-08-10 08:11:15

标签: c function struct

我似乎无法弄清楚为什么这不起作用,我传递'aHouse'变量一个返回House的函数。我是C的新手,所以我仍然试图了解一些事情。

#include <stdio.h>

typedef struct house {
    int id;
    char *name;
} House;

House getHouse()
{
    House *myHouse = NULL;

    char c = getchar();
    myHouse->id = 0;
    myHouse->name = c; /*only single char for house name*/

    return *myHouse
}

int main()
{
    House *aHouse = NULL;

    aHouse = getHouse();
}

1 个答案:

答案 0 :(得分:5)

第一: 您正在使用NULL指针并在“getHouse”函数中为其指定值。这是未定义的行为,应该提供访问冲突。

此外,您将通过getHouse中的值返回House对象并尝试分配指针类型。指针和值是两个不同的东西。

除非您想在堆上动态分配House,否则根本不需要指针。

House getHouse()
{
    House myHouse;

    char c = getchar();
    myHouse.id = 0;
    myHouse.name = c; /*only single char for house name*/

    return myHouse
}

int main()
{
    House aHouse;

    aHouse = getHouse();
}

编辑:为了提高效率,你可以像这样实现它:

void getHouse(House* h)
{ 
    char c = getchar();
    h->id = 0;
    h->name = c; /*only single char for house name*/
}

int main()
{
    House aHouse;    
    getHouse(&aHouse);
}

再次编辑: 同样在House结构中,因为名称只能是一个char,所以不要使用char *作为名称,只需使用char。

相关问题