我试图在Ubuntu 11.04中编译一个在Windows下运行良好的程序,但它给出了上述错误。我已经向导致错误的行添加了注释。代码如下:
route_input() {
    int num_routes;//Variable to act as the loop counter for the loop getting route details
    int x;
    char route_id[3];
    char r_source[20];
    char r_destination[20];
    int r_buses;
    printf("Please enter the number of routes used: \n");
    scanf("%d", &num_routes);
    char routes_arr[num_routes][10];//An array to hold the details of each route
    printf("\nNumber of routes is %d\n", num_routes);
    struct route r[num_routes];//An array of structures of type route (This line causes the error)
    fflush(stdin);
    for (x = num_routes; x > 0; x--) {
         printf("\nEnter the route number: ");
         scanf("%s", r[x].route_num);
         printf("Route number is %s", r[x].route_num);
         printf("\nEnter the route source: ");
         fflush(stdin);
         scanf("%s", r[x].source);
         printf("Source = %s", r[x].source);
         printf("\nEnter the route destination: ");
         fflush(stdin);
         gets(r[x].destination);
         printf("Destination = %s", r[x].destination);
         printf("\nEnter the number of buses that use this route: ");
         scanf("%d", &r[x].num_of_buses);
         printf("Number of buses = %d", r[x].num_of_buses);
    }
    for (x = num_routes; x > 0; x--) {
        printf("\n\n+++Routes' Details+++\nRoute number = %s, Source = %s, Destination = %s, Number of buses for this route = %d\n", r[x].route_num, r[x].source, r[x].destination, r[x].num_of_buses);
    }
}发布于 2012-05-01 17:40:25
出现该错误消息是因为您的struct route声明不完整。也就是说,在某个地方,你有一行字写着
struct route;不指定结构中的内容。这是完全合法的,并且允许编译器在知道结构中有什么之前就知道它存在。这允许它为不透明类型和正向声明定义指向struct route类型项的指针。
但是,编译器不能使用不完整的类型作为数组的元素,因为它需要知道结构的大小,才能计算数组所需的内存量以及从索引计算偏移量。
我要说的是,您忘记了包含定义路由结构的头文件。此外,Ubuntu的库中可能已经有一个名为struct route的不透明类型,因此您可能必须重命名您的结构以避免冲突。
发布于 2012-05-01 16:40:10
您需要包含定义struct route的头文件。
我不确定这是哪个头文件,而且在Linux和Windows之间可能会有所不同。
在Linux中,net/route.h定义了struct rtentry,这可能是您需要的。
发布于 2012-05-01 16:36:40
据我所知,C(至少GCC不会)不允许将变量作为数组索引,这就是为什么它会产生这个错误。请尝试使用常量。
这不会发生在多维数组中,因为行在多维数组中不是复数,但在单维数组中,数组索引必须是变量。
有些编译器确实允许这种行为,这就是为什么它不会在windows中产生错误的原因。
https://stackoverflow.com/questions/10395054
复制相似问题