将已定义的变量插入到数组中

Pau*_* A. 3 c arrays embedded

我不知道这是否可行,但有助于提出建议.

我有一个变量unsigned char Var_2_insert;,我有一个数组const unsigned char insert_here[4];.

该变量在运行时初始化var_2_insert = 225;.我们的想法是数组中的索引3应始终具有var_2_insert的值.所以我想尝试类似的东西

insert_here[4] = { 0x00, 0x02, 0x03, Var_2_insert};
Run Code Online (Sandbox Code Playgroud)

因此,每当我尝试读取数组时insert here,它将具有var_2_insert的当前值.现在我知道我是这样的:

#define Var_2_insert 225

这样做会顺利,但由于这个变量必须在运行时更新,我试过了

#define _VAR Var_2_insert
insert_here[4] = { 0x00, 0x02, 0x03, _VAR};
Run Code Online (Sandbox Code Playgroud)

但是不起作用.那我怎么能这样呢?我希望我的问题很清楚.

谢谢.

Roe*_*rel 5

你可以做的是有Var_2_insert一个指向数组中第3个索引的指针:

unsigned char insert_here[4]; // since it's updating it shouldn't be const
unsigned char *Var_2_insert = &(insert_here[3]);
//you just need to update the use of var_2_insert to dereference..
//  var_2_insert = 225 // <-- before
   *var_2_insert = 225 // <-- after
Run Code Online (Sandbox Code Playgroud)