繁体   English   中英

C结构示例,编译过程中的错误

[英]C struct example, errors during compilation

我试图熟悉C中的struct和指针,并且遇到了很多语法错误,例如“缺少';'”。 类型之前” 类型之前 缺少')'“未声明的标识符:'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);
        }
    }
}
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,然后声明功能。

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

在早期版本的C中,您不能在循环内声明I。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM