0

我有以下 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 ‘&amp;’ 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
4

2 回答 2

2

这个功能:

Room createRoom(char *name, float width, float length, float height);

应该像这样声明和定义:

struct Room createRoom(char *name, float width, float length, float height);
^^^^^^

在这条线上:

h.rooms[1] = &createRoom("lounge", 20, 20, 9);

您正在使用不允许这样做的临时地址。您可能会使用这样的临时变量:

h.rooms[0] = &hall;
struct Room hall2 = createRoom("lounge", 20, 20, 9);
h.rooms[1] = &hall2 ;

虽然这不是一个很好的解决方案,但您可能需要考虑createRoom动态分配 aRoom并返回 a Room*。您还将字符串文字分配给name并且address稍后可能会回来咬您,您可能还需要考虑为这些变量动态分配空间并使用类似的东西进行复制strcpyor strncpy

于 2013-06-11T20:07:02.683 回答
1

您也可以将您的声明从

struct Room
{
    float width;
    float length;
    float height;
    char *name;
};

typedef struct Room
{
    float width;
    float length;
    float height;
    char *name;
} Room;

和House类似。

于 2013-06-11T20:10:47.177 回答