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

发布于 2024-11-28 23:15:35 字数 440 浏览 0 评论 0原文

我似乎不明白为什么这不起作用,我将 '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();
}

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

桃气十足 2024-12-05 23:15:35

第一的:
您正在使用 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。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文