-
Structure Question
I wanted to ask, if I had a struct which looked like this:
Code:
typedef struct types
{
char *data1;
int *data2;
int data3
}type;
int main(....)
{
type a;
type *temp = NULL;
temp = &a + 1 *sizeof(char*) + 1*sizeof(int*);
......
}
Is the example correct? how can i get to int data3 without using the . or -> operator?
-
You need a semicolon after data3. If, for some reason, you need to get there without a . or a ->, I suppose you could use offsetof and some fancy pointer arithmetic.
-
yea but what would the pointer arithetic be? thats actually my question :)
-
offset gives you the offset from the start of the structure. You'll have to cast a pointer to the object to a char* (so that you can do arithmetic in bytes), and then add the offset to it to get a pointer to the specific data element you want, and then you have to dereference it as an int* to get the correct value.
-
Thank you very much for the info, ill try it and see.
-
> temp = &a + 1 *sizeof(char*) + 1*sizeof(int*);
Erm, No actually.
For one thing, structures can have padding space, so the offset of any member (except the first) is not necessarily the sum of the sizes of the preceding members.
Second, this is just far easier.
temp = &a.data3;
-
No to mention guaranteed to work on all compilers and platforms ;)