arrays - 如何在 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
在闪存中正确分配。
解决方案
推荐阅读
- gitlab - 找不到 gitlab“admin/runners”页面来注册共享跑步者
- java - 使用java从本地主机创建远程hdfs目录
- css - 更改为 Bootrap 4,我的导航栏现在看起来是蓝色的,并且没有一个下拉菜单与之前的位置对齐
- node.js - 出现错误:连接 ECONNREFUSED 127.0.0.1:3306
- c++ - 智能指针不能自动用作原始指针吗?
- flutter - 如何在 Dart 中为函数指定类型注释
- ubuntu - Electron dialog.showOpenDialog() 关闭 Ubuntu 18.10 上的应用程序
- r - 如何根据 R 中的其他两列分组来标准化列中的值?
- asynchronous - 如何返回递归获取的结果?
- r - 距离矩阵到按位置排序的距离重组向量