开发者

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. I am new to C so am still trying to get my head around a few things.

#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. 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. 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜