我正在尝试编写来自结构的变量指针数组。我的问题是结构内的变量具有不同的数据类型。
#include "stdlib.h"
typedef struct val {
unsigned char a;
unsigned char b;
unsigned short c;
unsigned int d;
} _letters;
void setup() {
Serial.begin(9600);
}
int var1 = 0;
void loop() {
_letters lt;
lt.a = 1;
lt.b = 2;
lt.c = 3;
lt.d = 4;
unsigned char *ptrLetters[4];
ptrLetters[0] = <.a;
ptrLetters[1] = <.b;
ptrLetters[2] = <.c; //here is the problem
ptrLetters[3] = <.d; //also here
var1 = (int)*ptrLetters[0];
Serial.println(var1);
}
这样做的目的是因为我想保存地址并通过数组的索引(*ptrLetters[index])从结构(我不能修改)访问变量,但问题是里面该结构有不同的数据类型,指针仅为 char 类型初始化。 我该如何动态更改它?
最佳答案
Pointer to object of any type can be implicitly converted to pointer to void (optionally cv-qualified); the pointer value is unchanged. The reverse conversion, which requires
static_cast
or explicit cast, yields the original pointer value:
void *ptrLetters[4];
ptrLetters[0] = <.a;
ptrLetters[1] = <.b;
ptrLetters[2] = <.c; //no more problem
ptrLetters[3] = <.d; //no more problem here as well
对于取消引用,在 C 中你可以简单地这样做:
unsigned char var1 = *((char*)ptrLetters[0]);
unsigned char var2 = *((char*)ptrLetters[1]);
unsigned short var3 = *((unsigned short*)ptrLetters[2]);
unsigned int var4 = *((unsigned int*)ptrLetters[3]);
因为你也用 C++ 标记了它,所以最好在 C++ 中使用 static_cast
。
unsigned char var1 = *(static_cast<unsigned char*>(ptrLetters[0]));
unsigned char var2 = *(static_cast<unsigned char*>(ptrLetters[1]));
unsigned short var3 = *(static_cast<unsigned short*>(ptrLetters[2]));
unsigned int var4 = *(static_cast<unsigned int*>(ptrLetters[3]));
关于c++ - 动态更改指向结构的指针数组的数据类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53316237/