home bbs files messages ]

Forums before death by AOL, social media and spammers... "We can't have nice things"

   comp.lang.c      Meh, in C you gotta define EVERYTHING      243,242 messages   

[   << oldest   |   < older   |   list   |   newer >   |   newest >>   ]

   Message 241,246 of 243,242   
   Bonita Montero to All   
   Re: Nice way of allocating flexible stru   
   08 Oct 25 11:09:27   
   
   From: Bonita.Montero@gmail.com   
      
   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.   
      
   --- SoupGate-Win32 v1.05   
    * Origin: you cannot sedate... all the things you hate (1:229/2)   

[   << oldest   |   < older   |   list   |   newer >   |   newest >>   ]


(c) 1994,  bbs@darkrealms.ca