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

cod*_*ght 0 c struct function

我似乎无法弄清楚为什么这不起作用,我传递'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();
}
Run Code Online (Sandbox Code Playgroud)

Pet*_*ete 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();
}
Run Code Online (Sandbox Code Playgroud)

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

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);
}
Run Code Online (Sandbox Code Playgroud)

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