1

So given this structure:

typedef struct {
    int* arr1;
    int* arr2;
} myStruct;

This answer described using a single malloc to allocate a myStruct and it's arrays at the same time:

myStruct* p = malloc(sizeof(*p) + 10 * sizeof(*p->arr1) + 10 * num * sizeof(*p->arr2);

if(p != NULL) {
    p->arr1 = (int*)(p + 1);
    p->arr2 = p->arr1 + 10;
}

What I'd like to know is there a similar way to do this with new?
Obviously I want to be able to allocate to a size that I receive at runtime as is done with the C example.

Community
  • 1
  • 1
Jonathan Mee
  • 37,899
  • 23
  • 129
  • 288

3 Answers3

7

You can allocate a block of memory using new with an array of char, then use placement new to call the constructor on that block of memory.

Community
  • 1
  • 1
Mark Ransom
  • 299,747
  • 42
  • 398
  • 622
  • It's also possible to call the allocation function `::operator new(size_t)` directly. Just be sure to match `new char[N]` with `delete [] ptr` and `::operator new(N)` with `::operator delete(ptr)` – Ben Voigt Sep 26 '16 at 15:12
1

In c++ we use new because it calls the constructors of the objects being allocated. So the proper way to achieve what you want is to have the constructor of the structure do the necessary allocations.

Ivaylo Strandjev
  • 69,226
  • 18
  • 123
  • 176
  • @Mgetz I am not saying OP should call new one by one. I am saying new should be called to allocate the array but the constructors of the objects should take care to allocated the memory they need. If the objects allocate a lot of memory themselves, then we use memory pools – Ivaylo Strandjev Nov 05 '13 at 16:21
1

Is there any reason you want to do it like in the link you provided? A little more context would help. Otherwise I would personally just use a constructor to do that:

    struct myStruct {
        int* arr1;
        int* arr2;
        myStruct(int num)
        {
                arr1 = new int[10];
                arr2 = new int[10*num];
        }
        ~myStruct()
        {
                delete[] arr1;
                delete[] arr2;
        }
};

int main()
{
        int num = 3;
        myStruct* a;
        a = new myStruct(3);
        delete a;
}
James Reed
  • 491
  • 3
  • 9
  • Given that he opened with an example of how it can be done in C, he may be concerned with the interaction between C modules and C++ modules, and want to keep the C++ code as similar to the C code as possible. – Justin Time - Reinstate Monica May 11 '17 at 20:45