Reputation: 57
I'm trying to code an array of pointers of variables from a struct. My problem is that the variables inside the struct have different data type.
#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);
}
The purpose of this is because I want to save the address and access the variables from the struct (which I CAN'T modify) by the index of the array (*ptrLetters[index]), but the problem is that inside the struct there are different data types and the pointer is initialised only for char types. How do I dynamically change that?
Upvotes: 2
Views: 358
Reputation: 721
You've not explained much on why you want to use only array of pointers or why you want to use pointers at all. Based upon what you're trying to do in your sample code, you can do it many ways.
The simplest would be to use a pointer to struct:
_letters *ptrLetter;
ptrLetter = <
var1 = ptrLetter->a;
You can also explore struct of pointers or use C++ classes to contain the data and pointer together.
Upvotes: 0
Reputation: 26800
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
For dereferencing, in C you can simply do this:
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]);
Since you tagged this with C++ also, it is better to use static_cast
in C++.
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]));
Upvotes: 1
Reputation: 18410
You can use an array of void (untyped) pointers:
void *ptrLetters[4];
ptrLetters[0] = <.a;
ptrLetters[1] = <.b;
ptrLetters[2] = <.c; //here is the problem
ptrLetters[3] = <.d; //also here
And you can then access your variables like this:
var1 = *((char*)ptrLetters[0]);
Note that you have to cast the void pointers back to the original type first for dereferencing. The conversion to int is then performed implicitly on assignment.
Upvotes: 0