[英]setting variable to the return type of a function
我似乎無法弄清楚為什么這不起作用,我將“aHouse”變量傳遞給 function ,它返回一個房子。 我是 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();
}
首先:您正在使用 NULL 指針並在“getHouse”function 中為其分配值。 這是未定義的行為,應該給出訪問沖突。
此外,您將通過 getHouse 的值返回 House object 並嘗試分配給指針類型。 指針和值是兩個不同的東西。
除非您想在堆上動態分配房屋,否則您根本不需要指針。
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。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.