Thread: newbie: pointers to structure questions

1. newbie: pointers to structure questions

Hi its me again,

im now looking into structures at im trying to figure out the meaning of the following code.

lets say we have 2 structures:
Code:
```struct struct1{
double i, a;
};

struct struct2 {
struct struct1 results[2];
};

struct struct1 *s1;
struct struct2 s2;

s1 = (struct struct1*)&s2  // what does this means????????```
i dun get what the commented line means. could someone please explain it to me? i appreciate all the help given to me

2. What you're looking at is a "gross hack" which is unfortunately possible in C. Understanding this, will not help you to understand structures any better. What you will get is a massive headache.

Move on to a better example, I think.

3. i still wish to know whats happening though heh

4. I am not sure what it means, but what it does is make s1 point to a struct2 object. Effectively, you are reinterpreting the struct2 object as one or more struct1 objects. In this case the effect is probably the same as s1 = s2.results, which is much easier to understand and is actually meaningful.

5. hey laserlet, thanks for make this clear for me. at least now i got an idea of what this does

6. http://cpwiki.sf.net/A_pointer_on_pointers
A pointer is only a variable with an address. So the & operator simple takes the address of the first struct and then an explicit cast is used to tell the compiler to make it into a pointer to struct2 and assigns it to the variable.
The type tells the compiler what value it is to expect, but in the low level stuff, there's no such thing as type, so you can cast it to whatever and the compiler will be happy, but your program will break.

It's quite a useful hack, if you use it properly.

7. how is this hack useful??

8. A dynamically allocated 2-dimensional+ array for example.

9. (NOTE: C++)
Polymorphism might be another:
Code:
`pp< std::vector< pp<CItemData> > > CListBox::GetAllItemData()`
GetAllItemData returns a vector of CItemData objects. However...
Code:
```typedef pp< std::vector< pp< Stuff::CItemDataTemplate<CString> > > > ItemDataVector;
ItemDataVector pData = *(ItemDataVector*)&m_Logs.GetAllItemData();```
I stored Stuff::CItemDataTemplate<CString> objects which I need to retrieve. Since it's derived from CItemData, it's perfectly fine to add it, but then I need to cast it back or use virtual functions to manipulate the data.
So in this case, a hack might be justified.

10. Note that this thread is in the C programming forum.

11. There may be many uses for such a hack, even in C++, as well as C. I'll just put a note, since manav did ask and is using C++, as well.

12. thanks Elysia for more in depth explaination.

Popular pages Recent additions