初始化结构元素数组时出错

时间:2018-12-19 15:14:49

标签: c arrays for-loop struct initialization

下午好,对于一个学校项目,我必须输入并显示客户端30天(1个月)的运动记录,客户端是一个包含天数组的结构,当我初始化程序时我会初始化我的客户矢量:

//Struct
typedef struct{
char name[100];
int dayOfBirth;
int monthOfBirth;
int yearOfBirth;
char address[100];
int phone;
int iRSNumber;
float height;
float weight;
int exerMinutes[30];

}client;

client clients[100] = {};


//initialize struct of clients
for(int i=0; i<100; i++){
    strcpy(clients[i].name, "NULL");
    strcpy(clients[i].address, "NULL");
    clients[i].height = 0.0;
    clients[i].yearOfBirth = 0;
    clients[i].monthOfBirth = 0;
    clients[i].dayOfBirth = 0;
    clients[i].iRSNumber = 0;
    clients[i].weight = 0.0;
    clients[i].phone = 0;
    for(int j = 0; j<30; j++){
        clients[i].exerMinutes[j] = 0;
    }
}

显示报告的代码:

system("cls");
printf("\nSHOW MONTHLY REPORT\n");
for(int i=0;i<30;i++){
    if((i+1)%2==0 && i!=0){
        printf("day %2d: %3d min\n", i+1, Client->exerMinutes[i]);
    }else{
        printf("day %2d: %3d min\t\t", i+1, Client->exerMinutes[i]);
    }
}

printf("\n\nPress Enter to continue");
system("pause >nul /nobreak");

但是,用于初始化月份数组的for()循环似乎不起作用,因为当我请求月份报告时,这是输出:

day  1: 100 min         day  2:   0 min
day  3:   0 min         day  4:   0 min
day  5:   0 min         day  6:   0 min
day  7:   0 min         day  8:   0 min
day  9:   0 min         day 10:   0 min
day 11:   0 min         day 12:   0 min
day 13:   0 min         day 14:   0 min
day 15:   0 min         day 16:   0 min
day 17:   0 min         day 18:   0 min
day 19:   0 min         day 20:   0 min
day 21:   0 min         day 22:   0 min
day 23:   0 min         day 24:   0 min
day 25:  10 min         day 26:   3 min
day 27: 1999 min                day 28: 1280070990 min
day 29:   0 min         day 30:   0 min

感谢您提供的帮助和/或建议。

1 个答案:

答案 0 :(得分:0)

代码运行良好,即,“结构”中的所有变量均以零或正好初始化。我尝试了一些更改。

问题在于以下几行:

if((i+1)%2==0    &&    i!=0){
        printf("day    %2d:    %3d    min\n",    i+1,    Client->exerMinutes[i]);
}else{
        printf("day    %2d:    %3d    min\t\t",    i+1,    Client->exerMinutes[i]);
}

您已经使用了指针来构造“客户端”,但尚未初始化,这就是得到意外结果的原因。请记住,在此“客户”中,您使用了大写字母“ C”。希望这会有所帮助:)