Click here to Skip to main content
14,924,665 members
Please Sign up or sign in to vote.
3.00/5 (4 votes)
See more:
what is meaning of this?
C++
struct texture
{
    unsigned char r[10];
};

struct texarray
{
    texture mode[1];
};

we have one structure with a member as a member of an other structure.
I don't understand the meaning of it?
could you explain for me with an example, please?
Posted
Updated 19-Oct-12 6:11am
v4
Comments
Keith Barrow 19-Oct-12 10:46am
   
No, I don't understand it either. Unless there is something subtle and c++y going on (I'm a c# dev with a little c++ experience about 10 years ago) I doubt the code above is well written. Might be worth trawling through the code and seeing where it is used to see what it is intended for.
Sergey Chepurin 19-Oct-12 12:19pm
   
And why this question has been downvoted???

This may be a common trick used in C programming, but it's hard to tell without seeing the context it is used in. I am referring to the practice of allocating a struct with arbitrary number of elements dynamically without need to treat it as a pointer, or the overhead of even having a pointer:

C++
texarray* foo(std::size_t sz) {
   texarray* pta = reinterpret_cast<texarray*>(new texture[sz]);
   for (std::size_t i = 0; i < sz; ++i) {
      strcpy(pta->mode[i], "undefined");
   }
   return pta;
}
void bar(textarray* pta) {
   delete [] reinterpret_cast<texture*>(pta);
}

int main() {
   textarray* p = foo(15);
   // now do something with it
   // ...

   // and release again:
   bar(p);
   return 0;
}


Note that this trick usually requires a special function to release the memory correctly again, or else you'll end up with memory leaks or, worse, run-time errors.
   
C++
// this structure contains up to 10
// characters in the array named r
struct texture
{
    unsigned char r[10]
}
// this structure contains up to 1
// texture structures in the array
// named mode
struct texarray
{
    texture mode[1]
}

However, the definition mode[1] allows the developer to allocate larger, variable length arrays (using new or malloc()) which can then handle different amounts of data. This is a useful way of defining a structure when it is not known, at compile time, exactly how many elements may be needed, or presented when reading variable length data.
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900