将变量设置为函数的返回类型
我似乎不明白为什么这不起作用,我将 '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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
第一的:
您正在使用 NULL 指针并在“getHouse”函数中为其赋值。这是未定义的行为,应该会导致访问冲突。
此外,您还从 getHouse 按值返回 House 对象,并尝试分配给指针类型。指针和值是两个不同的东西。
除非您想在堆上动态分配 House,否则您根本不需要指针。
编辑:为了提高效率,您可以像这样实现它:
再次编辑:
同样在 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.
EDIT: for the sake of efficiency, you could implement it like this though:
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.