sbit a1=P1^0;
sbit a2=P1^1;
sbit a3=P1^2;
void function setValue(unsigned char dt,unsigned char index){
-----
}
这个函数功能是为前面声明的某个变量赋值,比如调用setValue(10,2),运行结果就是a2==10,这个问题的关键是怎样根据传递来的index值来设置对应的变量,我不希望用if else或switch之类的写法,因为实际应用中我可能有几十个这样的变量。用a+index或=dt
“a”+index=dt显然都不行,该怎么写呢,谢谢!
第1个回答 2013-08-28
我以前也这样想过,后来发现用指针能解决,先定义unsigned a1,a2,a3,……;
然后定义一个指针unsigned char *p;
运行p=&a1;
setValue(x,y)
p+=y-1;
*p=x;
如setValue(10,2)
结果a2就是10;
不懂追问
然后定义一个指针unsigned char *p;
运行p=&a1;
setValue(x,y)
p+=y-1;
*p=x;
如setValue(10,2)
结果a2就是10;
不懂追问
第2个回答 2013-08-28
字符串末尾追加,可以用strcat,将你传递来的index追加到字符a后面,但是这要求你传入的是字符型。
第3个回答 2013-08-28
用数组代替你的变量。
例如:你需要10个变量。
unsigned char cTable[10];
void function setValue(unsigned char dt,unsigned char index)
{
cTable[index] = dt;
}追问
{
PORT0,
PORT1,
PORT2,
PORT3,
}enPORT;
void function setValue(enPORT Pn,unsigned char dt,unsigned char index)
{
switch (Pn)
{
case PORT0:
if (dt == 1) P0 |= 1 << inde;
else P0 &= ~(1 << inde);
break;
case PORT1:
if (dt == 1) P1 |= 1 << inde;
else P1 &= ~(1 << inde);
break;
}
}
例如:你需要10个变量。
unsigned char cTable[10];
void function setValue(unsigned char dt,unsigned char index)
{
cTable[index] = dt;
}追问
这个我也想到过,但是网上都说sbit型不支持数组定义
追答抱歉,题没看清。
如果可以,那你改变一下程序的结构:
typedef enum{
PORT0,
PORT1,
PORT2,
PORT3,
}enPORT;
void function setValue(enPORT Pn,unsigned char dt,unsigned char index)
{
switch (Pn)
{
case PORT0:
if (dt == 1) P0 |= 1 << inde;
else P0 &= ~(1 << inde);
break;
case PORT1:
if (dt == 1) P1 |= 1 << inde;
else P1 &= ~(1 << inde);
break;
}
}
如有错误请指正。
本回答被网友采纳