c - 如何访问结构数组中的值

标签 c arrays xcode structure

结构:

struct tod{
    int minute;
    int hour;
};
struct event
{
    int start, end;
}; 

数组:

int main (void)
{
    struct event schedule[] = {{{9,45},{9,55}},{{13,0},
        {14,20}},{{15,0},{16,30}}};
    printf ("%d\n", freetime (schedule,3,8,0));

}

为什么当我执行 schedule[0].end 时我得到 9 而不是 45? 或 schedule[1].end 我得到 13 而不是 55。如何获取数组中的分钟值?第一组 3 个大括号不是开始时间吗?第二个设定结束时间?我不知道如何使用上面的结构来保存这些值。

这是我的代码

int freetime (struct event schedule[], int n, int hour, int min)
{
    struct tod time1;
    struct tod time2;
    int i;
    int result = 1;
    for (i=0; i<n; i++)
    {
        time1.hour = schedule[i].start;
        time1.minute = schedule[i].end;
        i++;
        time2.hour = schedule[i].start;
        time2.minute = schedule[i].end;
        if(hour >= time1.hour && hour < time2.hour)
        {
            if(min >= time1.minute && min < time2.minute)
            {
                result = 0;
                break;
            }
        }
    }
    return result;
}

如果指定的时间(小时和分钟)不是任何预定事件的一部分,freetime 应该返回 1;否则返回 0。值 n 指定包含计划的数组的大小。

最佳答案

您的事件结构可能应该如下所示:

struct event
{
    tod start, end;
}; 

因为您试图将 tod 存储在 int 中。这导致您将第一个“时间”存储在第一个事件中,而第二个“时间”被放入您的第二个事件中(依此类推)

试试这个,用于测试:

//returns true if tod1 comes before tod2
bool tod_before(tod tod1, tod tod2)
{
     return !((tod1.hour > tod2.hour) 
            || ((tod1.hour == tod2.hour) 
                && (tod1.minute > tod2.minute))
}


int freetime (struct event schedule[], int n, int hour, int min)
{
    struct tod test_time;
    struct tod time1;
    struct tod time2;
    int i;
    int result = 1;

    test_time.hour = hour;
    test_time.minute = min;

    //handle edge cases
    if (tod_before(test_time, schedule[0].start) || tod_before(schedule[n-1].end, test_time)
    {return 1;}

    //handle general case
    for (i=0; i<n-1; i++)
    {
        time1 = schedule[i].end;
        time2 = schedule[i+1].start;

        if (tod_before(time1, time) && tod_before(time, time2))
        {return 1;}
    }
    //if we get to here, then time wasn't found in a break
    return 0;
}

当然,这是假设每个事件都是按顺序进行的。

关于c - 如何访问结构数组中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26632942/

相关文章:

arrays - 算法 - 最小减法

javascript - 如何创建嵌套的 JSON 数据类型?

ios - 在标签上打印来自终端的文本?

c - 如何定义与结构数组 C 一起使用的宏

C 线程变量在从另一个线程声明后具有值

c++ - 在 gtk3 Textview 中显示字符串时出现问题

arrays - 如何检查数组是否包含 Scala 2.8 中的特定值?

ios - ios 9 模拟器中的 mapView 是空白的

ios - 在 UIView 中加载多个 tableview(UIView Controller )

c++ - 如果 C 有结构,为什么它不是 OOP