Home > Mobile >  Two dimensional array initilization in Mplab XC16
Two dimensional array initilization in Mplab XC16

Time:01-31

I have defined the two-dimensional array inside the typedef struct as,

#define MAX_STAGES_IIR 20

 typedef struct {
     float A[MAX_STAGES_IIR]; // Input Gain
     float a[MAX_STAGES_IIR][2]; // input stage coff
     
     float b[MAX_STAGES_IIR][3]; // output stage coff
    // float B[MAX_STAGES_IIR]; // output gain
     
     float Xdash[MAX_STAGES_IIR][2];
     
     float iir_k[MAX_STAGES_IIR];//
     float iir_r[MAX_STAGES_IIR];//

     float iir_outStage[MAX_STAGES_IIR];
}IIRFilter;

When assigning values to the array use this method,

IIRFilter BpfHX_iir1;

    BpfHX_iir1.A = { 0.131726 , 0.131726 , 0.12435, 1.0f }; // gain 

    BpfHX_iir1.a = {{-1.63410, 0.82662},{-1.87089, 0.91410},{-1.6652, 0.7513}}; // a

    BpfHX_iir1.b = {{1, 0, -1},{1, 0, -1},{1, 0, -1}}; // b

but the Mplab XC16 can't build this method.

gives the same error message for all three arrays,

expected expression before '{' token

expected expression before '{' token

expected expression before '{' token

what is the reason for that?

is there a correct method to do that in XC16?

CodePudding user response:

Initialize BpfHX_iir1 in the usual way.
Use float constants and not double ones for the float array. (Append an f.)

IIRFilter BpfHX_iir1 = { //
  .A = {0.131726f, 0.131726f, 0.12435f, 1.0f}, //
  .a = { {-1.63410f, 0.82662f}, {-1.87089f, 0.91410f}, {-1.6652f, 0.7513f}}, //
  .b = { {1, 0, -1}, {1, 0, -1}, {1, 0, -1}} //
};

All members of BpfHX_iir1 will be initialized. Those not explicitly coded above will have a zero bit-pattern.


To assign an array *1 via memcpy() at a later time is easy if the compiler is C99 compliant. Use a compound literal.

void foobar(void) {
  IIRFilter BpfHX_iir1;
  //                   v-------------------------------- compound literal ---------v
  memcpy(BpfHX_iir1.A, (float[MAX_STAGES_IIR]){0.131726f, 0.131726f, 0.12435f, 1.0f}, sizeof BpfHX_iir1.A);
  ...
}

Or the old fashion way:

  const float A0[MAX_STAGES_IIR] = {0.131726f, 0.131726f, 0.12435f, 1.0f};
  memcpy(BpfHX_iir1.A, A0, sizeof BpfHX_iir1.A);

*1 Arrays cannot be simply assigned in C. They can be copied via memcpy(), just like any object.

  • Related