将结构数组传递给另一个函数

问题描述 投票:0回答:1

我仍然是一个新手,试图让自己通过。

我已经编写了这段代码,在其中创建了一个称为depot的总线结构数组,现在我将其保留为全局变量,这样我可以更轻松地通过每个函数来获取它而不会遇到指针问题错误之类的,因为在涉及指针并将其与其他事物(如结构和数组等)混合使用时,我还是有点虚弱。

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


struct Bus{         //structure method defined in the question itself
    int BusID;          //unique value. Example: 1
    int RouteID;        //unique value. Example: 1001
    time_t schedule;    //Scheduled departure time
};


//question states to create this array
struct Bus* Depot[10];      //Declaring an array of Bus structure named Depot of size 10.


int createBuses();
int printBuses();
int scheduleBuses();
int scheduleBuses();
int alignupBuses();
int releaseBus();
int emergency();


int main(){
    srand(time(NULL)); //Initialize the srand with the current time

    time_t mytime; //A variable of the type time_t to store the current date and time

    int choice = 0;

    printf("Welcome to the bus management system!\n\n");
    printf("Do you wish to create a new fleet of 10 buses?\n");
    printf("Press (1) to continue\n");

    while(choice != 1){
        scanf("%d", &choice);
    }

    createBuses();
    printf("Success!\n\n");


    printf("You have exited the system\nThank you!\nHave a nice day!");
    return 0;
}


int createBuses(){
    for(int f=1; f<10; f++){
        Depot[f] = (struct Bus*) malloc (sizeof(struct Bus));
        Depot[i]->BusID = rand();
        Depot[i]->RouteID = rand();     
    }

}


int printBuses(){
    /*int array[10];
    int count=0;
    char * time_str;
    while(count<3){
        time_str = ctime(&array[count].t); //convert and store the time into a character pointer
        printf("Bus id = %s -> Time --> %s \n",array[count].id, time_str);
        count++;
    }
    */
}

如果我只是将struct Bus* Depot[10];保留为全局变量,我知道如何解决。但是由于使用它们是一种不好的做法,因此我想将其放在主要位置并习惯于以这种方式进行编码。但是,当我这样做时,出现了一些我不明白该如何解决的错误,我应该在int printBuses()createBuses()的括号内输入什么

PS-到目前为止,createBuses()函数内部的代码是为全局变量制作的,但如果我将全局变量放入int printBuses()函数,则main()函数为该代码。

因此,我将如何修改create函数,以及如何将该软件仓库变量从主要传递给create和printf函数。非常感谢您的帮助。

c arrays pointers linked-list structure
1个回答
0
投票

您的数组(仓库)不是结构的数组,而是指向结构的指针的数组在createBus中:您的循环运行9次(不是数组大小的10次),我是谁?

尝试纠正这些错误,它应该可以工作

© www.soinside.com 2019 - 2024. All rights reserved.