lundi 28 mai 2018

C++ way of creating a structure with variable number of items

I need to create a memory region with variable number of items at the end. Something that I can write like this:

#pragma pack(push,0)
struct MyData
{
    int noOfItems;
    int buffer[0];
};
#pragma pack(pop)

MyData * getData(int size)
{
     bufferSize = size* sizeof(int) + sizeof(MyData ::noOfItems);
     MyData * myData= (MyData *)new char[m_bufferSize];
     return myData;
}

This code works on VS 2015 with a warning that array of size of zero is not standard

A bit of search showed me that this is a C hack and is not supported on C++.

Array with size 0

Array of zero length

What happens if I define a 0-size array in C/C++?.

How can I do this in C++

Aucun commentaire:

Enregistrer un commentaire