If you are using c++ then you shouldn't reinvent the wheel, just use vectors:

#include <vector>

std::vector< std::vector< Stock > > StockVector;

// do this as many times as you wish
StockVector.push_back( std::vector< Stock >() );

// Now you are adding a stock to the i-th stockarray
StockVector[i].push_back( Stock() );

Edit:

I didn't understand your question, if you just want to have and array of arrays allocated on the heap just use:

Stock** StockArrayArray = new Stock*[n]; // where n is number of arrays to create
for( int  i = 0; i < n; ++i )
{
    StockArrayArray[i] = new Stock[25];
}

// for freeing
for( int i = 0; i < n; ++i )
{
    delete[] StockArrayArray[i];
}
delete[] StockArrayArray;
Answer from akaltar on Stack Overflow
🌐
w3resource
w3resource.com › cpp-exercises › dynamic-memory-allocation › cpp-dynamic-memory-allocation-exercise-6.php
C++ Dynamic Memory Allocation: Creating an array of objects with new operator
November 28, 2025 - We then use the new operator to dynamically create an array of MyClass objects and assign its address to a pointer called dynamicArray.
Discussions

Dynamic array of objects in C++ - Stack Overflow
I'm trying to create a dynamic array of objects, similar to ArrayLists in Java. More on stackoverflow.com
🌐 stackoverflow.com
A dynamic array objects in a class - C++ Forum
I'm designing a program that mimics a small banking program. There's two classes I'm trying to design right now, which is the transaction class and the account class. I need the account class to contain an array of transaction objects, but I need it to be sized dynamically as the account performs ... More on cplusplus.com
🌐 cplusplus.com
Declaration of a Dynamic Array of Objects
Hi guys, Embarrassingly, I'm having a little trouble declaring a global array of objects dynamically. Right now I've gotten the following working: Sketch #include "MyClass.h" #define ROWS 3 MyClass arr[ROWS]; Header … More on forum.arduino.cc
🌐 forum.arduino.cc
0
0
July 27, 2010
The best/easiest way to do generic dynamic arrays in C
This is a well known pattern for implementing generics (see, for example, stb_ds , sds , or my own CC ). Whether it's "the best" is debatable. It does have some drawbacks: You need to be careful about data alignment. malloc and friends return a pointer appropriately aligned for any datatype (i.e. aligned for max_align_t), but when you add an offset to it in order to account for the container header, the resulting pointer may not be correctly aligned for the user's chosen datatype. In this particular case, your header consists of two size_t, which is typically eight bytes, and alignof( max_align_t ) is typically 16, so you'll be fine in practice. But it's easy to neglect this point, and people often seem to do so. The API macros can never be fully safe because the ones that mutate the container must assign back to the container handle (assuming you don't want to burden the user with this task, like sds does) and therefore evaluate the handle twice. I talk a little bit about my approach to mitigating this issue at the bottom of this comment . Making API macros behave like proper functions (e.g. they can be called inside expressions, and they can return a value indicating whether an insertion operation succeeded or failed due to memory exhaustion) is difficult. You can do it, but the techniques necessary are neither pretty nor documented anywhere at present (except perhaps in my comment here ). u/brewbake pointed out that for the user, the semantics of container handles can be surprising. Of course, structs suffer from the same issue if the user starts trying to copy and assign them willy-nilly, but the problem is that your dynamic array doesn't look at all like a struct. This is why in my own library, every API macro takes a pointer to the container handle as its first argument, not the handle itself. In other words, CC container handles both behave and look/are used exactly like structs, even though under the hood they are pointers. This makes the semantics predictable for users, but the downside is that it's easy to forget an & and get blasted with a cascade of cryptic compiler errors. More on reddit.com
🌐 r/C_Programming
19
19
March 26, 2025
🌐
Cplusplus
cplusplus.com › forum › beginner › 23308
Dynamic Array of Objects - C++ Forum
May 4, 2010 - I'm working with a simple object "Fraction." It holds a numerator and a denominator. I've also make a member function called .print() that simply prints the fraction. When I try to use the .print() on a member of a dynamic array I get an error when I try to compile.
🌐
GeeksforGeeks
geeksforgeeks.org › c language › dynamic-array-in-c
Dynamic Array in C - GeeksforGeeks
July 23, 2025 - We can create a dynamic array in C by using the following methods: ... The “malloc” or “memory allocation” method in C is used to dynamically allocate a single large block of memory with the specified size.
🌐
Cplusplus
cplusplus.com › forum › beginner › 124251
A dynamic array objects in a class - C++ Forum
I'm designing a program that mimics a small banking program. There's two classes I'm trying to design right now, which is the transaction class and the account class. I need the account class to contain an array of transaction objects, but I need it to be sized dynamically as the account performs ...
🌐
Arduino Forum
forum.arduino.cc › forum 2005-2010 (read only) › software › syntax & programs
Declaration of a Dynamic Array of Objects - Syntax & Programs - Arduino Forum
July 27, 2010 - Hi guys, Embarrassingly, I'm having a little trouble declaring a global array of objects dynamically. Right now I've gotten the following working: Sketch #include "MyClass.h" #define ROWS 3 MyClass arr[ROWS]; Header #ifndef MyClass_h #define MyClass_h #include "WProgram.h" class MyClass { public: MyClass(); MyClass(int var); int getVar(); private: int _var; }; #endif You can probably guess what MyClass.cpp file looks like.
Find elsewhere
🌐
Florida State University
cs.fsu.edu › ~myers › cop3330 › notes › dma.html
Dynamic Allocation in Classes
Dynamically create a new array of desired size. (This step will require a second pointer for temporary use). ... Adjust pointers so that the new array has the desired name This process is used in the following code example. The above link is to an example that involves two classes and uses dynamic memory allocation. The classes are Entry and Directory. Entry -- An object of this class type represents a single entry in a phone book.
🌐
Quora
quora.com › How-do-I-create-a-dynamic-array-in-C
How to create a dynamic array in C - Quora
Answer (1 of 3): You can create a dynamic array in C by allocating the initial array on the heap using malloc(), then reallocating the array to the required size using realloc() before accessing its elements.
🌐
Reddit
reddit.com › r/c_programming › the best/easiest way to do generic dynamic arrays in c
r/C_Programming on Reddit: The best/easiest way to do generic dynamic arrays in C
March 26, 2025 -

I recently came across libcello which enables alot of magical stuff ontop of C by utilizing what they call "Fat Pointers" which are essentially pointers with additional information concerning the data it points to, what caught my attention was when the author described an example of how to implement arrays using this approach, so I decided to try out a very simple example and its actually very elegant and easy

The way you do it is basically have a generic header structure with additional data you want to preserve

typedef struct ptr_header{
    size_t len;
    size_t cap;
}ptr_header;

when you want to create a new dynamic array you just allocate extra memory for the header

int *arr = NULL;

// allocate 10 elements + space for the header
arr = malloc(sizeof(ptr_header) + sizeof(*ar) * 10);

// skip the header and make arr point to the actual data
arr = (void *)((char *)arr + sizeof(ptr_header));

// access the length by going back and cast as header 
((ptr_header *)arr-1)->len = 0;

// access the capacity the same way
((ptr_header *)arr-1)->cap = 10;

now you can get the length and capacity by very simple arithmetic and you can do your reallocations and all the nice stuff you want to do and get creative with some macro magic

The best thing about it is you dont have to create a struct for every dynamic array of the type and that subscripting works -which I didnt even think of when I implemented it- and everything works

here is a simple full example to get the point across

Top answer
1 of 5
23
This is a well known pattern for implementing generics (see, for example, stb_ds , sds , or my own CC ). Whether it's "the best" is debatable. It does have some drawbacks: You need to be careful about data alignment. malloc and friends return a pointer appropriately aligned for any datatype (i.e. aligned for max_align_t), but when you add an offset to it in order to account for the container header, the resulting pointer may not be correctly aligned for the user's chosen datatype. In this particular case, your header consists of two size_t, which is typically eight bytes, and alignof( max_align_t ) is typically 16, so you'll be fine in practice. But it's easy to neglect this point, and people often seem to do so. The API macros can never be fully safe because the ones that mutate the container must assign back to the container handle (assuming you don't want to burden the user with this task, like sds does) and therefore evaluate the handle twice. I talk a little bit about my approach to mitigating this issue at the bottom of this comment . Making API macros behave like proper functions (e.g. they can be called inside expressions, and they can return a value indicating whether an insertion operation succeeded or failed due to memory exhaustion) is difficult. You can do it, but the techniques necessary are neither pretty nor documented anywhere at present (except perhaps in my comment here ). u/brewbake pointed out that for the user, the semantics of container handles can be surprising. Of course, structs suffer from the same issue if the user starts trying to copy and assign them willy-nilly, but the problem is that your dynamic array doesn't look at all like a struct. This is why in my own library, every API macro takes a pointer to the container handle as its first argument, not the handle itself. In other words, CC container handles both behave and look/are used exactly like structs, even though under the hood they are pointers. This makes the semantics predictable for users, but the downside is that it's easy to forget an & and get blasted with a cascade of cryptic compiler errors.
2 of 5
3
You can have a variable length array at the end of a struct. So struct vec { int len; int cap; struct type vals[]; }. Then allocate with malloc(sizeof(struct vec) + cap * sizeof(struct type)) would be the same thing.
🌐
Lobsters
lobste.rs › s › gyar3m › writing_dynamic_array_c
Writing a Dynamic Array in C | Lobsters
October 24, 2023 - You would have to store the interval between items in the backing array--I think this is called the "stride" and I'm not sure how to get that in C. ... yes, it stores only pointers to objects. Like you said, you can store values as well by tracking the size of the object to be stored and do a byte-wise copy of the passed in object into the array slots.
🌐
Medium
medium.com › @sohaib.arshid101 › dynamic-arrays-in-c-an-implementation-guide-4a959de94332
Dynamic arrays in C: An implementation guide | by curious&dumb | Medium
March 5, 2024 - The problem with VLAs is that one cannot change the size of the array after initialization (which is variable), eventually causing the same problem as the one faced while using stack arrays. This is where dynamic arrays allow users to create arrays that can be varied at runtime, unlike the fixed-length/variable-length arrays.
🌐
Medium
medium.com › @nick-stambaugh › dynamic-arrays-in-c-fdc8a2f66b53
Dynamic Arrays in C. Understanding array manipulation is… | by Nick Stambaugh | Medium
May 4, 2024 - Dynamic Arrays in C Understanding array manipulation is fundamental for software engineers. A dynamic array is an array that can automatically resize itself when its capacity is exceeded. This is …
🌐
DEV Community
dev.to › gtanyware › dynamic-arrays-in-c-24oj
Dynamic arrays in C++ - DEV Community
February 16, 2024 - It differs only very slightly from the previous StringArray. Here’s the code: #ifndef OBJECTARRAY #define OBJECTARRAY /* ObjectArray is a memory-efficient class for managing arrays of arbitrary objects.
🌐
InformIT
informit.com › articles › article.aspx
12.2. Dynamic Arrays | Working with Dynamic Memory in C++ | InformIT
The language defines a second kind of new expression that allocates and initializes an array of objects. The library includes a template class named allocator that lets us separate allocation from initialization. For reasons we’ll explain in § 12.2.2 (p. 481), using an allocator generally provides better performance and more flexible memory management. Many, perhaps even most, applications have no direct need for dynamic arrays.
🌐
Quora
quora.com › Why-in-C-cant-you-declare-a-dynamic-array-of-objects-with-parameterized-constructors
Why in C++ can't you declare a dynamic array of objects with parameterized constructors? - Quora
Because C++ needs to know how to initialize each object when you allocate an array, and the language designers provided only a limited array-initialization form for new. Two linked reasons explain the restriction: 1) Syntax and semantics of new[] were designed for default construction and for value-initialization/aggregate initialization, not for passing different constructor arguments per-element.
🌐
Quora
quora.com › How-do-you-dynamically-allocate-memory-to-an-array-of-objects-in-C
How to dynamically allocate memory to an array of objects in C++ - Quora
Answer (1 of 3): The real-life answer is that you do not. std::vector will take care of all the intricacies. If you absolutely need to do it, you must first allocate raw memory using new[] or malloc. Then you need to call placement new to invoke the constructor on each object. Then upon dealloca...
🌐
Cplusplus
cplusplus.com › forum › beginner › 22982
Dynamic array of objects in a class. - C++ Forum
April 28, 2010 - I have an assignment wherein i have to make a dynamic array of objects, which has to be made in another class. This leads me to write something like this in the constructor of ClassA: ClassA::ClassA(int myMax, string paramB) { myArray = new ClassB[myMax]; ...
Top answer
1 of 7
138

For building containers you obviously want to use one of the standard containers (such as a std::vector). But this is a perfect example of the things you need to consider when your object contains RAW pointers.

If your object has a RAW pointer then you need to remember the rule of 3 (now the rule of 5 in C++11).

  • Constructor
  • Destructor
  • Copy Constructor
  • Assignment Operator
  • Move Constructor (C++11)
  • Move Assignment (C++11)

This is because if not defined the compiler will generate its own version of these methods (see below). The compiler generated versions are not always useful when dealing with RAW pointers.

The copy constructor is the hard one to get correct (it's non trivial if you want to provide the strong exception guarantee). The Assignment operator can be defined in terms of the Copy Constructor as you can use the copy and swap idiom internally.

See below for full details on the absolute minimum for a class containing a pointer to an array of integers.

Knowing that it is non trivial to get it correct you should consider using std::vector rather than a pointer to an array of integers. The vector is easy to use (and expand) and covers all the problems associated with exceptions. Compare the following class with the definition of A below.

class A
{ 
    std::vector<int>   mArray;
    public:
        A(){}
        A(size_t s) :mArray(s)  {}
};

Looking at your problem:

A* arrayOfAs = new A[5];
for (int i = 0; i < 5; ++i)
{
    // As you surmised the problem is on this line.
    arrayOfAs[i] = A(3);

    // What is happening:
    // 1) A(3) Build your A object (fine)
    // 2) A::operator=(A const&) is called to assign the value
    //    onto the result of the array access. Because you did
    //    not define this operator the compiler generated one is
    //    used.
}

The compiler generated assignment operator is fine for nearly all situations, but when RAW pointers are in play you need to pay attention. In your case it is causing a problem because of the shallow copy problem. You have ended up with two objects that contain pointers to the same piece of memory. When the A(3) goes out of scope at the end of the loop it calls delete [] on its pointer. Thus the other object (in the array) now contains a pointer to memory that has been returned to the system.

The compiler generated copy constructor; copies each member variable by using that members copy constructor. For pointers this just means the pointer value is copied from the source object to the destination object (hence shallow copy).

The compiler generated assignment operator; copies each member variable by using that members assignment operator. For pointers this just means the pointer value is copied from the source object to the destination object (hence shallow copy).

So the minimum for a class that contains a pointer:

class A
{
    size_t     mSize;
    int*       mArray;
    public:
         // Simple constructor/destructor are obvious.
         A(size_t s = 0) {mSize=s;mArray = new int[mSize];}
        ~A()             {delete [] mArray;}

         // Copy constructor needs more work
         A(A const& copy)
         {
             mSize  = copy.mSize;
             mArray = new int[copy.mSize];

             // Don't need to worry about copying integers.
             // But if the object has a copy constructor then
             // it would also need to worry about throws from the copy constructor.
             std::copy(&copy.mArray[0],&copy.mArray[c.mSize],mArray);

         }

         // Define assignment operator in terms of the copy constructor
         // Modified: There is a slight twist to the copy swap idiom, that you can
         //           Remove the manual copy made by passing the rhs by value thus
         //           providing an implicit copy generated by the compiler.
         A& operator=(A rhs) // Pass by value (thus generating a copy)
         {
             rhs.swap(*this); // Now swap data with the copy.
                              // The rhs parameter will delete the array when it
                              // goes out of scope at the end of the function
             return *this;
         }
         void swap(A& s) noexcept
         {
             using std::swap;
             swap(this.mArray,s.mArray);
             swap(this.mSize ,s.mSize);
         }

         // C++11
         A(A&& src) noexcept
             : mSize(0)
             , mArray(NULL)
         {
             src.swap(*this);
         }
         A& operator=(A&& src) noexcept
         {
             src.swap(*this);     // You are moving the state of the src object
                                  // into this one. The state of the src object
                                  // after the move must be valid but indeterminate.
                                  //
                                  // The easiest way to do this is to swap the states
                                  // of the two objects.
                                  //
                                  // Note: Doing any operation on src after a move 
                                  // is risky (apart from destroy) until you put it 
                                  // into a specific state. Your object should have
                                  // appropriate methods for this.
                                  // 
                                  // Example: Assignment (operator = should work).
                                  //          std::vector() has clear() which sets
                                  //          a specific state without needing to
                                  //          know the current state.
             return *this;
         }   
 }
2 of 7
13

I'd recommend using std::vector: something like

typedef std::vector<int> A;
typedef std::vector<A> AS;

There's nothing wrong with the slight overkill of STL, and you'll be able to spend more time implementing the specific features of your app instead of reinventing the bicycle.