首页 > 解决方案 > 如何在 C 中获取包含 const 数组的 const 结构的正确大小

问题描述

我得到一个包含 const char 数组的结构的错误大小。

示例(Arduino 代码):

#include <Streaming.h>

struct my_struct_t {
    uint8_t  len;
    const char str[];
};

// Macro to init struct from string
#define MAKE_STRUCT(s)  { .len = sizeof(s), {.str = s} }

#define my_str "30-03-2020"

const struct my_struct_t my_struct = MAKE_STRUCT(my_str);

struct my_struct2_t {
    uint8_t index;
    uint8_t size;
};

const my_struct2_t my_struct2 = {0, sizeof(my_struct)};

void setup() {
  // put your setup code here, to run once:
    while(!Serial); delay(10);
    Serial << ("sizeof(my_str) = ") << sizeof(my_str) << endl;
    Serial << ("my_struct.len = ") << my_struct.len << endl;
    Serial << ("sizeof(my_struct) = ") << sizeof(my_struct) << endl;
    Serial << ("my_struct2.size = ") << (my_struct2.size) << endl;
}

void loop() {
}

串行窗口中打印的值:

sizeof(my_str) = 11
my_struct.len = 11
sizeof(my_struct) = 1
my_struct2.size = 1

问题是 my_struct 的大小错误(预期为 1+11=12),这样 my_struct2 将被初始化为错误的值。

我究竟做错了什么?

如何获得my_struct要用于的正确尺寸值my_struct2

编辑

只想提一下,my_struct在闪存中正确分配。

标签: arraysstructconstantsflexible-array-member

解决方案


推荐阅读