From: already5chosen@yahoo.com   
      
   On Wed, 8 Oct 2025 11:23:13 +0200   
   Bonita Montero wrote:   
      
   > Am 08.10.2025 um 11:09 schrieb Bonita Montero:   
   > > Am 08.10.2025 um 08:35 schrieb Kaz Kylheku:    
   > >> Jonas Lund of https://whizzter.woorlic.org/ mentioned this   
   > >> trick in a HackerNews comment:   
   > >>   
   > >> Given:   
   > >>   
   > >> struct S {   
   > >> // ...   
   > >> T A[];   
   > >> };   
   > >>   
   > >> Don't do this:   
   > >>   
   > >> malloc(offsetof(S, A) + n * sizeof (T));   
   > >>   
   > >> But rather this:   
   > >>   
   > >> malloc(offsetof(S, A[n]));   
   > >>   
   > >> It's easy to forget that the second argument of offsetof is a   
   > >> designator, not simply a member name.   
   > >>    
   > >    
   > > In a real language:   
   > >    
   > > #include    
   > > #include    
   > > #include    
   > >    
   > > using namespace std;   
   > >    
   > > template   
   > > struct flex_base   
   > > {   
   > > T &operator []( size_t i )   
   > > {   
   > > return static_cast( *this ).m_arr[i];   
   > > }   
   > > virtual ~flex_base() {};   
   > > };   
   > >    
   > > template   
   > > struct flex_array : flex_base>   
   > > {   
   > > virtual ~flex_array() {};   
   > > private:   
   > > template   
   > > friend struct flex_base;   
   > > std::array m_arr;   
   > > };   
   > >    
   > >    
   > > int main()   
   > > {   
   > > auto &fb = *new flex_array();   
   > > for( size_t i = 0; i != 100; ++i )   
   > > fb[i] = "hello world";   
   > > }   
   > >    
   > > Somewhat more complicated to declare, but much shorter and   
   > > more readable usage.   
   > > C really sucks.    
   >    
   > OMG, I was blind:   
   >    
   > T * new T[N];   
      
   You don't understand the meaning of the word 'flexible'.   
   The whole point of it is that N is unknown at compile time.   
      
   Formally speaking, flexible array members are not supported in   
   inferior tongue that you call "real language" although they can be   
   emulated and in practice will work with any production-quality   
   compiler.   
   However, if I am not mistaken, it works just because implementors are   
   sane people, rather than because the language itself provides sane   
   guarantees.   
      
   --- SoupGate-Win32 v1.05   
    * Origin: you cannot sedate... all the things you hate (1:229/2)   
|