struct无法在结构中定义新类型和结构

时间:2013-06-11 20:03:22

标签: c types struct

我有以下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);
    }
}

}

我在编译期间得到以下内容,我不知道如何修复。谁能告诉我该怎么做并告诉我为什么房间不被认可为一种类型?

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

2 个答案:

答案 0 :(得分: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动态分配Room并返回Room*。您还要将字符串文字分配给nameaddress,这些文字可能会在以后再次出现,您可能还需要考虑为这些变量动态分配空间并使用strcpy之类的内容进行复制或strncpy

答案 1 :(得分:1)

您也可以从

更改声明
struct Room
{
    float width;
    float length;
    float height;
    char *name;
};

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

和House相似。