C数组结构的初始化和调用

zysjyyx4  于 2023-05-16  发布在  其他
关注(0)|答案(3)|浏览(116)

在C语言STM32typedef中初始化和调用结构体的正确方法是什么

struct motor_struct {
    uint32_t yellow_clicks;
    uint32_t green_clicks;
    uint8_t pin;
    GPIO_TypeDef port;
    _Bool green_hall;
    _Bool yellow_hall;

} motors[4];


//motors(yellow_clicks) = {0,0,0,0}; - *compile without error but what is gone inside?*
motors[0].yellow_clicks  = 0; *- get an error*
z9zf31ra

z9zf31ra1#

你只能做这样的事情:

motors[0].yellow_clicks  = 0;

在一个函数中。如果你想在编译时初始化你的结构数组,你需要像这样:

struct motor_struct {
    uint32_t yellow_clicks;
    uint32_t green_clicks;
    uint8_t pin;
    GPIO_TypeDef port;
    _Bool green_hall;
    _Bool yellow_hall;

} motors[4] = {
    {0, 0, 1, GPIOA, false, false}, // motors[0]
    {1, 1, 2, GPIOB, true, false},  // motors[1]
    {0, 1, 1, GPIOC, true, true},   // motors[2]
    {1, 2, 3, GPIOA, true, true}    // motors[3]
};

当然,使用对你有意义的价值观。

wnavrhmk

wnavrhmk2#

为了给一个结构体 * 赋值 * 而不是在声明时 * 初始化 * 它,你要么需要一个接一个地设置成员,要么使用一个临时的复合文字:

motors[i] = (struct motor_struct) { 0, 0, 0, 0, false, false };

是否对结构体使用typedef有点主观,尽管在这种情况下,我认为它会使代码更具可读性。

typedef struct 
{
  uint32_t yellow_clicks;
  uint32_t green_clicks;
  GPIO_TypeDef port;
  uint8_t pin;
  _Bool green_hall;
  _Bool yellow_hall;
} motor_t;

motor_t motors[4] = { ... };

(Also注意我做的结构填充优化-GPIO_TypeDef可能是一些32位指针,所以它应该在pin之上声明,否则你将白白浪费内存。
也可以考虑指定的初始化器:

motor_t motors[4] =
{
  [0] = { 
          .yellow_clicks = 123,  .green_clicks = 456,
          .port = PORTX,         .pin = 1,
          .green_hall = false,   .yellow_hall = false,
        },

  [1] = ...
};
zf9nrax1

zf9nrax13#

由于您使用STM32CUBEIDE标记了此变量,因此值得注意的是,当您声明静态全局变量时,启动代码将该变量置零。
归零意味着变量的内存将被0填充。
因此,在下面的motors数组将被归零。

struct motor_struct {
    uint32_t yellow_clicks;
    uint32_t green_clicks;
    uint8_t pin;
    GPIO_TypeDef port;
    _Bool green_hall;
    _Bool yellow_hall;

};

static motor_struct motors[4];

https://www.st.com/resource/en/user_manual/um2609-stm32cubeide-user-guide-stmicroelectronics.pdf

相关问题