C中的结构初始化问题

时间:2011-09-22 15:22:31

标签: c struct

我似乎在设置结构中的数组值时出现问题,编译器中出现了无意义的错误:

  

在'{'标记

之前预期的primary-expression

我理解结构必须“存在”才能接受值,并且它作为指向一个的指针存在。我希望你向我解释我做错了什么以及如何实现我的目标。

struct EventCheckData {
  unsigned long refresh_time;
  unsigned long last_execution_ms; //Can also serve to delay at startup
  byte signal_type;
};

struct ClockData {
    struct EventCheckData event_array[4];
    byte event_count;
    unsigned long last_absolute_time;
    UISignal *warning_signals;
}; 



 void ResetClock(UISignal *warning_signal, struct ClockData *clock_data, unsigned long absolute_time) { 
    if(SignalCheckValue(warning_signal, RESET_CLOCK, 1)) {
        extern volatile unsigned long timer0_overflow_count;
        timer0_overflow_count = 0;
        clock_data->last_absolute_time = absolute_time;
        clock_data->event_count = 3;
        (clock_data->event_array)[0] = { .refresh_time = 3000UL, .last_execution_ms = 0UL, .signal_type = WATER_PUMP_ON};
//      clock_data->event_array[1] = {10000UL, 0UL, EXPORT_LOG};
//      clock_data->event_array[2] = {100000UL, 0UL, EXTERNAL_CONNECTION};
        SignalSet(warning_signal, RESET_CLOCK, 0);
    }
}

谢谢 保罗·内维斯

3 个答案:

答案 0 :(得分:4)

您分配它的方式看起来像初始化程序。您需要分配,尝试复合文字:

clock_data->event_array[0] = (struct EventCheckData){ .refresh_time = 3000UL, ...};

答案 1 :(得分:4)

(clock_data->event_array)[0] = { .refresh_time = 3000UL, .last_execution_ms = 0UL, .signal_type = WATER_PUMP_ON};不是初始化。这是作业。

你不能在赋值中使用初始化语法。

使用C99,您应该能够使用复合文字,例如

(clock_data->event_array)[0] = (struct EventCheckData){ .refresh_time = 3000UL, .last_execution_ms = 0UL, .signal_type = WATER_PUMP_ON};

答案 2 :(得分:2)

没有任何C99内容你可以简单地使用:

void ResetClock(UISignal *warning_signal, struct ClockData *clock_data, unsigned long absolute_time) { 
if(SignalCheckValue(warning_signal, RESET_CLOCK, 1)) {
  extern volatile unsigned long timer0_overflow_count;
  timer0_overflow_count = 0;
  clock_data->last_absolute_time = absolute_time;
  clock_data->event_count = 3;
  {
    struct EventCheckData a[]={ {3000UL, 0UL, WATER_PUMP_ON},
                                {10000UL, 0UL, EXPORT_LOG},
                                {100000UL, 0UL, EXTERNAL_CONNECTION}};
    memcpy(clock_data->event_array,a,sizeof a);
  }
  SignalSet(warning_signal, RESET_CLOCK, 0);
}