gpt4 book ai didi

c - 使用嵌入式C中的指定初始化程序初始化结构。“期望表达式”

转载 作者:行者123 更新时间:2023-12-05 01:35:22 25 4
gpt4 key购买 nike

我正在尝试初始化一个结构,并将值分配给该结构变量。

我的结构:


  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;



当我尝试声明和初始化变量时,我使用了指定的初始化程序:


arm_pid_instance_q31 pitch_pid_instance
={
.A0 = 0,
.A1 = 0,
.A2 = 0,
.State ={0,0,0},
.Kd = 0,
.Ki = 0,
.Kp = 0
};



我正在将Keil µVision4和ARM C编译器用于嵌入式项目。
编译此代码时,编译器返回错误#29:预期表达式。错误发生在初始化代码的每一行上。

我读到这是用ANSI C99编写代码时要走的路,但这在我的情况下不起作用。 How to initialize a struct in ANSI C99

我知道我可以编写“错误”代码:


 arm_pid_instance_q31 pitch_pid_instance;
pitch_pid_instance.A0 = 0;
etc...



但...

有小费吗?



更新:
以下代码有效:


  arm_pid_instance_q31 pitch_pid_instance = {0,0,0,0,0,0,0,0,0};



但是,这又不是一个特别漂亮的代码或实现方式。

最佳答案

如果要将所有内容初始化为0,则只需使用通用零初始化程序即可(并忽略编译器提供的任何虚假警告)。
通用零初始化程序是有效的C89,C99,C11(我相信它在C89之前也是有效的)。

arm_pid_instance_q31 pitch_pid_instance = {0};
struct somecomplexstruct array[1000] = {0};


...我确定你明白了



如果要初始化为0以外的值,并且没有C99编译器,则需要单独进行处理,例如在“错误”代码中。

或者,您可以分离需要初始化的部分并复制(而不初始化)它们

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 */

关于c - 使用嵌入式C中的指定初始化程序初始化结构。“期望表达式”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11841900/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com