home bbs files messages ]

Just a sample of the Echomail archive

COMPLANC:

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

 Message 241,247 of 243,097 
 Bonita Montero to All 
 Re: Nice way of allocating flexible stru 
 08 Oct 25 11:23:13 
 
From: Bonita.Montero@gmail.com

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];

--- 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