-
Quick Answer...
I have a pointer.... is there a way to chagne what data type it is?
Like i have 5 structures and i need to use the same variable but be able to switch betwen which type it is in the program. I dont really want to just cast it to another one cuz it get all bloated code. but can i just do someting to delete the current pointer and make it again w/ a different data type?
-
You could declare a void pointer and then make it point to the appropriate type.
I'm not exactly sure if this is what you want.
Eg.
Code:
typedef struct{/*...*/}ONE;
typedef struct{/*...*/}TWO;
typedef struct{/*...*/}THREE;
typedef struct{/*...*/}FOUR;
typedef struct{/*...*/}FIVE;
int main()
{
void *ptr;
ptr = new ONE;
delete ptr;
ptr = new TWO;
delete ptr;
ptr = new THREE;
delete ptr;
ptr = new FOUR;
delete ptr;
ptr = new FIVE;
delete ptr;
return 0;
}
-
You could always redefine the 5 structures as 5 classes that derive from a common base class. A pointer to a class can be assigned to derived classes as well.
Void pointers are handy for passing addresses, but you have to typecast them each time you use them.
-
OK, I understand your problem now.
If you used that method then you'd have to cast the pointer each time you used it.
Code:
int main()
{
void *ptr;
ptr = new ONE;
((ONE*)ptr)->foo = NULL;
delete ptr;
return 0;
}
You could define a structure that had pointers to the other structures as members.
Code:
typedef struct{char* foo;}ONE;
typedef struct{char* foo;}TWO;
typedef struct{char* foo;}THREE;
typedef struct{char* foo;}FOUR;
typedef struct{char* foo;}FIVE;
typedef struct
{
ONE* one;
TWO* two;
THREE* three;
FOUR* four;
FIVE* five;
}ALL;
int main()
{
ALL* ptr = new ALL;
ptr->one = new ONE;
ptr->one->foo = NULL;
delete ptr->one;
return 0;
}