I'm new to C++ and am trying to figure out how to dereference a pointer to a struct, so that I can retrieve the values of the members in that struct. In buildCar(), I'd like to be able to print the year of the car as well as the specs of the car (which, when set, will be a pointer to another structure). I'm able to print out the memory address where the car1 struct is stored, but I'm having trouble figuring out the correct syntax to use to deference this pointer. I've tried using (*) for derefencing, and -> instead of . to refer to the struct's members, but have had no luck thus far. Any help is appreciated. Thank you!
struct item {
int id;
void *myData;
};
struct car {
unsigned int year;
char* specs;
};
void buildCar(item item1);
int main() {
struct item item1;
item1.id = 1;
struct car car1;
car1.year = 2019;
item1.myData = &car1;
buildCar(item1);
}
void buildCar(item item1){
cout << "address of car1 = " << item1.myData;
}
I'm having trouble figuring out the correct syntax to use to deference this pointer.
You cannot indirect through a void pointer. You can only indirect through non-void pointers.
A solution: Change the type of the pointer:
struct item {
int id;
struct car *myData;
};
You can then access the members of the pointed object using the indirecting member access operator ->
.
Presumably there could be other types of items than cars, so a void * might be necessary.
In pure C++, there are better alternatives such as inheritance, std::variant
and std::any
, depending on usage requirements.
Given that Mango mentioned in a comment that the header is C, the better alternatives might not be available, and void*
may be necessary indeed.
In such case, the void pointer can be converted back to the original pointer type which the void pointer was converted from using static_cast
. The behaviour of converting to a wrong type will be undefined, so great care must be taken.