C struct示例,编译期间的错误

时间:2014-02-21 00:29:47

标签: c struct compiler-errors

我试图熟悉struct和C中的指针,我遇到了一堆语法错误,比如“missing';'在键入“”缺少')之前键入“”未声明的标识符:'i'“。一切似乎都很好,我知道i已经宣布,我似乎没有遗漏任何;)

#include <stdlib.h>
#include <stdio.h>

#pragma warning(disable: 4996)
struct Room; 
struct House;

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

struct House
{
    char *address;
    struct Room *rooms[10]; 
};

int main(int argc, char* argv[])
{

    struct House h;
    h.address = "10 Palace Road";  
    for(int i = 0; i < 10; i++) // 6 errors occur here
    {
        h.rooms[i] = NULL;
    }
    struct Room hall;
    hall.width = 10;
    hall.length = 12;
    hall.height = 9;
    hall.name = "Hall";

    h.rooms[0] = &hall;
    printHouse(h);
    system("PAUSE");
    return 0;

}

void printHouse(struct House house)
{

    printf(house.address);
    printf("\n\n\n");

    for (int i=0; i<10; i++)
    {
        if (house.rooms[i] != NULL)
        {
            struct Room r = *house.rooms[i];
            printf("Room # %d: %s", i+1, r.name);
        }
    }
}

3 个答案:

答案 0 :(得分:4)

printf(house.address);

应该是

printf("%s",house.address);

此外,您必须声明您的函数printhouse,因为您已在main之后定义它。

#include <stdlib.h>
#include <stdio.h>
#pragma warning(disable: 4996)
struct Room; //you don't need this

**EDIT**
struct House
{
char *address;
struct Room *rooms[10];
};
void printHouse(struct House house);

首先声明House然后是函数。

答案 1 :(得分:3)

int i;
for (i = 0; i < 10; i++){
    //...
}

在早期版本的C中,你不能在循环中声明我。

答案 2 :(得分:2)

某些版本的C编译器不允许在循环中声明“i”。尝试在'main()'的开头单独声明'i'。这应该工作。