[英]Initialize Array of Pointers to Array of Structs
I'm trying to find a logical way to initialize a large number of arrays containing a large number of initialized structs so that a function can select a struct from the table and read its values. 我试图找到一种逻辑方法来初始化包含大量已初始化结构的大量数组,以便函数可以从表中选择一个结构并读取其值。 I wrote some very simple test code, but I know I am doing something wrong along the way.
我写了一些非常简单的测试代码,但是我知道在此过程中做错了什么。
The contents of "struct_test.h" “ struct_test.h”的内容
int my_test_var = 0;
typedef struct
{
int a;
int b;
}my_struct;
const my_struct tbl1[] =
{
{0x01,0x02},
{0x03,0x04},
};
const my_struct tbl2[] =
{
{0x05,0x06},
{0x07,0x08},
};
const my_struct *struct_tbl[] =
{
tbl1,
tbl2,
};
The contents of "struct_test.c" “ struct_test.c”的内容
#include "struct_test.h"
int main(void)
{
if(struct_tbl[0][0].a == 0x01)
my_test_var = 0x01;
return 0;
}
I would expect to read the value of my_test_var as 0x01, but it returns as 0. I think something might be wrong with how I am writing struct_tbl, but I am not sure. 我希望将my_test_var的值读取为0x01,但它返回为0。我认为我编写struct_tbl的方式可能有问题,但是我不确定。
I'd appreciate any help. 我将不胜感激。 Sorry if this is a very simple question, I'm just an EE trying to learn to write better code!
抱歉,如果这是一个非常简单的问题,我只是一个试图学习编写更好代码的EE!
Edit: Declared int my_test_var externally, still same result. 编辑:从外部声明为int my_test_var,结果仍然相同。
Edit2: Updated code to include complete files. Edit2:更新了代码以包含完整的文件。 The weird result I get is that when I compile and run on my 64-bit Linux machine, I get the expected result.
我得到的奇怪结果是,当我在64位Linux机器上编译并运行时,得到了预期的结果。 However, when I run on my 16-bit micro (Freescale Star12) my_test_var returns as zero.
但是,当我在16位微型计算机(Freescale Star12)上运行时,my_test_var返回为零。 Through a watch window I can see each element of struct_tbl points to NULL rather than tbl1 and tbl2.
通过观察窗口,我可以看到struct_tbl的每个元素都指向NULL,而不是tbl1和tbl2。
if(struct_tbl[0][0].a == 0x01)
int my_test_var = 0x01;
Get rid of the int
keyword. 摆脱
int
关键字。 This is declaring a (nested) variable which is in scope in the if
statement only. 这是在(仅)
if
语句中声明一个(嵌套的)变量。 After the if
statement ends, the variable disappears. if
语句结束后,变量消失。
if (struct_tbl[0][0].a == 0x01)
my_test_var = 0x01;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.