我对C语法有点问题。我想构建一个struct数组。但它返回
预期的声明说明符或'city'之前的'...'
这是我的代码
#include <stdio.h>
#include <string.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
struct City {
int plateNumber;
char name[32];
double area;
int population;
int populationDensity;
int cityCenterPopulation;
char region[32];
double latitude;
double longitude;
};
struct City cities[81];
#define Struct_Size sizeof(struct City)
void printCityData(cities[], int i);
void readFile();
void readFile(){
int fd = open("data.dat", O_RDONLY);
if(fd<0) {
printf("Error while opening file!");
return;
}
int i;
for (i = 0; i < 81; i++) {
while(read(fd,&cities[i], Struct_Size)>0) {
printCityData(cities[i],i);
}
}
}
void printCityData(cities[], int i) {
printf("CITIES\n");
printf("plateNumber: %d\n", cities[i].plateNumber);
printf("name: %s\n", cities[i].name);
printf("area: %lf\n", cities[i].area);
printf("population: %d\n", cities[i].population);
printf("populationDensity: %d\n", cities[i].populationDensity);
printf("cityCenterPopulation: %d\n", cities[i].cityCenterPopulation);
printf("region: %s\n", cities[i].region);
printf("latitude: %lf\n", cities[i].latitude);
printf("longitude: %lf\n", cities[i].longitude);
}
int main(int argc, char const *argv[]) {
readFile();
return 0;
}
我该如何解决这个问题?
答案 0 :(得分:3)
我相信,问题是由于
中的cities[]
之前缺少数据类型
void printCityData(cities[], int i)
应该是
void printCityData(struct City cities[], int i)
请记住,cities
是变量,而不是数据类型。 FWIW,在前向声明的情况下,您实际上可以省略变量名称而不是变量类型。
那就是说,实际上,cities
在这里是全局变量,你不需要将它作为参数传递。您可以将功能签名缩小为
void printCityData(int i) {
并将其称为
printCityData(i);
答案 1 :(得分:0)
问题是你没有提到城市的数据类型,而且你正在使用与我想象的不同的数据类型调用该函数。我做了所需的更改:
#include <stdio.h>
#include <string.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
struct City {
int plateNumber;
char name[32];
double area;
int population;
int populationDensity;
int cityCenterPopulation;
char region[32];
double latitude;
double longitude;
};
struct City cities[81];
#define Struct_Size sizeof(struct City)
void printCityData(struct City cities[], int i); //cities is an array of struct City
void readFile();
void readFile(){
int fd = open("data.dat", O_RDONLY);
if(fd<0) {
printf("Error while opening file!");
return;
}
int i;
for (i = 0; i < 81; i++) {
while(read(fd,&cities[i], Struct_Size)>0) {
printCityData(cities,i);
}
}
}
void printCityData(struct City cities[], int i) {
printf("CITIES\n");
printf("plateNumber: %d\n", cities[i].plateNumber);
printf("name: %s\n", cities[i].name);
printf("area: %lf\n", cities[i].area);
printf("population: %d\n", cities[i].population);
printf("populationDensity: %d\n", cities[i].populationDensity);
printf("cityCenterPopulation: %d\n", cities[i].cityCenterPopulation);
printf("region: %s\n", cities[i].region);
printf("latitude: %lf\n", cities[i].latitude);
printf("longitude: %lf\n", cities[i].longitude);
}
int main(int argc, char const *argv[]) {
readFile();
return 0;
}