HCS12 - Const Array of Struct-pointers

取消
显示结果 
显示  仅  | 搜索替代 
您的意思是: 
已解决

HCS12 - Const Array of Struct-pointers

跳至解决方案
2,125 次查看
sebasira
Senior Contributor I

Hello everybody!

 

I'm working with a "constant array of pointers to a struct". (Please excuse my english, I'm not sure if that's written allright).

Let's put it into code so you can understand me:

 

 

typedef struct{
      byte Tx_F;      // Tx Flag
      byte cmd;       // Command Number
}typeTxCMD;


typeTxCMD Command_00={0,25};
typeTxCMD Command_01={0,32};
typeTxCMD Command_02={0,44};


const typeTxCMD* TxCommand_Table[]={
    &Command_00,
    &Command_01,
    &Command_02
}

 

Then, I want to set the Tx Flag of a Command, but that command depends on the value of a variable, let's name it as "var".

So, I do this:

 

 

TxCommand_Table[var]->Tx_F = 1;

 

And when compiling, and error pops up: "C1830: Modifiable lvalue expected"

To avoid this I did a little "trick" and works fine, but I want to know why it doesn't work the other way.

Here's what I did:

 

 

typeTxCMD* temp;

temp = TxCommand_Table[var];
temp->Tx_F = 1;

 

Please I hope you guys can give me a hand here.

Best Regards!

标签 (1)
0 项奖励
回复
1 解答
930 次查看
CompilerGuru
NXP Employee
NXP Employee

That's actually a pretty common mistake, the problem is that not the array is const, but instead it contains pointers to const elements.

To use a const array with pointers to non const structs move the const after the *:

 

typeTxCMD* const TxCommand_Table[...

 

Daniel

 

在原帖中查看解决方案

0 项奖励
回复
4 回复数
931 次查看
CompilerGuru
NXP Employee
NXP Employee

That's actually a pretty common mistake, the problem is that not the array is const, but instead it contains pointers to const elements.

To use a const array with pointers to non const structs move the const after the *:

 

typeTxCMD* const TxCommand_Table[...

 

Daniel

 

0 项奖励
回复
930 次查看
crane
Contributor III

It all makes perfect sense once you realize that you should read from right to left:

 

TxCommand_Table (is a ) const * (to a) typeTxCMD

 

Håkan

0 项奖励
回复
930 次查看
sebasira
Senior Contributor I

Thanks for that tip!! It's very useful!

 

 

0 项奖励
回复
930 次查看
sebasira
Senior Contributor I

Thank you very much!!!!!

0 项奖励
回复