I am trying to initialize a struct, and assign values to the struct variables.
My struct:
typedef struct { q31_t A0; q31_t A1; q31_t A2; q31_t State[3]; q31_t Kp; q31_t Ki; q31_t Kd; } arm_pid_instance_q31;
And when I try to declare and initialize the variable I use the designated initializer:
arm_pid_instance_q31 pitch_pid_instance ={ .A0 = 0, .A1 = 0, .A2 = 0, .State ={0,0,0}, .Kd = 0, .Ki = 0, .Kp = 0 };
I am using Keil µVision4 and the ARM C compiler for an embedded project. When compiling this code, compiler returns Error #29: Expected an expression. The error occurs on every line in the initialization code.
I read that this is the way to go when writing in ANSI C99, but this doesn't work in my case. How to initialize a struct in ANSI C99
I know i can write the "bad" code:
arm_pid_instance_q31 pitch_pid_instance; pitch_pid_instance.A0 = 0; etc...
but...
Any tips?
Update: The following code works:
arm_pid_instance_q31 pitch_pid_instance = {0,0,0,0,0,0,0,0,0};
But again, this isn't a particulary pretty code or way of doing it.
If you're initializing every thing to 0 just use the universal zero initializer (and ignore any spurious warning the compiler gives you).
The universal zero initializer is valid C89, C99, C11 (and I believe it was also valid pre-C89).
arm_pid_instance_q31 pitch_pid_instance = {0};
struct somecomplexstruct array[1000] = {0};
... I'm sure you get the point
If you want to initialize to values other than 0, and you don't have a C99 compiler, then you need to do it individually, like in your "bad" code.
Or you could separate the parts that need initialization and copy (not initialize) them
struct substruct {
q31_t Kp;
q31_t Ki;
q31_t Kd;
};
struct arm_pid_instance_q31 {
q31_t A0;
q31_t A1;
q31_t A2;
q31_t State[3];
struct substruct K;
};
struct substruct tmp = {42, -1, -1000};
struct arm_pid_instance_q31 pitch_pid_instance; /* uninitialized */
memcpy(&pitch_pid_instance.K, &tmp, sizeof tmp); /* copy values */
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With