I have two struct first f;
structures struct first f;
struct second s;
and a pointer to one of them pointer
. How to figure out which pointer points to?
- And what language? - Cristopher Plasma
4 answers
Imagine you are working with memory. A pointer is just an address in memory. Having brought it to a certain type and having tried to refer to the fields of the structure, you will receive any data, but not the fact that they will be correct. My advice is do not do such complicated things.
UPD. You can, of course, embed a field in each structure as the first byte, which will indicate the type of structure.
- oneIf you dig into the source code of Ruby, then the wash is done there. in style: struct Object {byte type;} struct String {Object * value;}. lead to Object. and watch what type you have. - Alexander Korsak
- 2Since there is no RTTI in C, a special field in the structure is the right approach. - stanislav
Apparently something like this:
struct first f; struct second s; void f(void* pointer) { if (pointer == &f) printf("first\n"); if (pointer == &s) printf("second\n"); }
In general, the question is not correct) Och is difficult to understand what is meant)
- oneah that's what% meant) - psyhitus
If we are talking about structures, then obviously:
switch (pointer) { case &struct1: ... case &struct2: ... }
Perhaps in C you cannot make a switch
by pointers, but I think the idea is clear.
And if we are talking about types, then it is worth overloading (EMNIP, you can do the same)
void type_sensitive(struct1* data) { ... } void type_sensitive(struct2* data) { ... }
I don’t remember exactly, but I can try to cast the pointer to one of the types, if the address is NULL, it means that the pointer is of a different type.
- this is in C ++ via dynamic_cast possible - psyhitus
- It will not work. Static type conversion (we are talking about X, judging by the labels?) Simply shifts the value of the pointer, adding or subtracting a certain number. The correctness of the resulting pointer is not checked. - ߊߚߤߘ