我有以下 C 代码。
它应该创建一个房屋类型和一个房间类型。但是,似乎无法识别房间类型,因为我无法创建房间类型的功能。
代码后是编译错误。
#include <stdlib.h>
#include <stdio.h>
//create type Room.
struct Room
{
float width;
float length;
float height;
char *name;
};
//create type House.
struct House
{
char *address;
/*Rooms in house are an array of pointers. Each pointer to a Room.*/
struct Room *rooms[10];
};
//protype functions.
void printHouse (struct House house);
Room createRoom(char *name, float width, float length, float height);
int main()
{
//create house h.
struct House h;
h.address = "10 Palace Road";
for (int i = 0; i < 10; i++)
h.rooms[i] = NULL;
//create a room (hall) without use of createRoom. Successful.
struct Room hall;
hall.width = 10;
hall.length = 12;
hall.height = 9;
hall.name = "Hall";
h.rooms[0] = &hall;
h.rooms[1] = &createRoom("lounge", 20, 20, 9);
printHouse(h);
return 0;
}
Room createRoom(char *name, float width, float length, float height)
{
struct Room r;
r.width = width;
r.length = length;
r.height = height;
r.name = name;
return r;
}
//prints contents of the house. Working okay.
void printHouse (struct House house)
{
printf("%s",house.address);
printf("\n\r\n\r");
for (int i=0; i<10; i++)
{
if (house.rooms[i] != NULL)
{
struct Room r = *house.rooms[i];
printf("Room #%d: %s", i, r.name);
}
}
}
在编译期间,我收到以下内容,我不知道如何修复。谁能告诉我在这里做什么并告诉我为什么 Room 没有被识别为一种类型?
gcc -std=c99 -c -Wall -ggdb -c -o struct.o struct.c
struct.c:24:1: error: unknown type name ‘Room’
struct.c: In function ‘main’:
struct.c:40:15: error: lvalue required as unary ‘&’ operand
struct.c: At top level:
struct.c:49:1: error: unknown type name ‘Room’
struct.c: In function ‘createRoom’:
struct.c:57:2: error: incompatible types when returning type ‘struct Room’ but ‘int’ was expected
struct.c:58:1: warning: control reaches end of non-void function [-Wreturn-type]
make: *** [struct.o] Error 1