将结构数组作为参数传递给C中的函数

时间:2018-04-08 10:34:52

标签: c arrays function struct

我正在尝试将其打印出来,但它仍然失败,并且只打印地址,我是C的新手,并且不太确定如何解决这个问题。

我有两个struct和两个方法,

struct Date {
    char week_day[30];
    int day[31];
    int month[12];
};

struct Holiday {
    char name[80]; //name
    struct Date date; //date
};


void printHols(struct Holiday hol[]){
    printf("Holidays in 2018\n");

    for (int i=0; i<2; i++) {
        printf("%d / %d \t - %s \t - %s", hol[i].date.day, hol[i].date.month, hol[i].date.week_day, hol[i].name);
    }
}

void holidaysValues(){
    struct Holiday holiday={{"New Year",{"Monday",1,1}}, {"Some Holiday",{"Tuesday",2,3}} };

//passing this struct below  doesn't work as expected, prints addresses of how[I].date.day, hol[I].date.month

    printHols(&holiday);
}

欢迎所有建议。 感谢

1 个答案:

答案 0 :(得分:2)

我已经修改了一下你的代码。

首先,我确定您打算在日期和月份使用整数而不是它们的数组。 而你忘了将[]添加到假期。 在你做完之后 - 没有必要在printHols(&amp; holiday)中提供假期参考;

我还在printf中添加了\ n,但它只是为了获得更好的输出。

#include <stdio.h>

struct Date {
    char week_day[30];
    int day;
    int month;
};

struct Holiday {
    char name[80]; //name
    struct Date date; //date
};


void printHols(struct Holiday hol[]){
    printf("Holidays in 2018\n");

    for (int i=0; i<2; i++) {
        printf("%d / %d \t - %s \t - %s \n", hol[i].date.day, hol[i].date.month, hol[i].date.week_day, hol[i].name);
    }
}

void main(){
    struct Holiday holiday[] = {{"New Year",{"Monday",1,1}}, {"Some Holiday",{"Tuesday",2,3}} };

    printHols(holiday);
}
相关问题