简体   繁体   English

将变量设置为 function 的返回类型

[英]setting variable to the return type of a function

I can't seem to figure out why this will not work, I am passing the 'aHouse' variable a function which returns a House.我似乎无法弄清楚为什么这不起作用,我将“aHouse”变量传递给 function ,它返回一个房子。 I am new to C so am still trying to get my head around a few things.我是 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();
}

First: You are using a NULL pointer and assigning values to it in the 'getHouse' function.首先:您正在使用 NULL 指针并在“getHouse”function 中为其分配值。 This is undefined behaviour and should give an access violation.这是未定义的行为,应该给出访问冲突。

Also, you are returning a House object by value from getHouse and trying to assign to a pointer type.此外,您将通过 getHouse 的值返回 House object 并尝试分配给指针类型。 A pointer and a value are two different things.指针和值是两个不同的东西。

You don't need pointers here at all unless you want to allocate your Houses dynamically on the heap.除非您想在堆上动态分配房屋,否则您根本不需要指针。

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

EDIT: for the sake of efficiency, you could implement it like this though:编辑:为了提高效率,你可以像这样实现它:

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

EDIT again: Also in the House structure, since the name can only be one char, don't use a char* for name, just use a char.再次编辑:同样在 House 结构中,由于名称只能是一个字符,因此不要使用 char* 作为名称,只需使用 char。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM