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
🌐
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.
Discussions

Dynamic Array of Objects - C++ Forum
When I try to use the .print() on a member of a dynamic array I get an error when I try to compile. Isn't a pointer to an object usable as an object and can use the dot (.) modifier to call member functions? This is the error I get when I try to compile. ... What I'd like to be able to is send the dynamic array though a for loop and print them all out. ... You should consider using the -> operator when working with pointers, rather than the . operator. It makes the intention ... More on cplusplus.com
🌐 cplusplus.com
May 4, 2010
How common are dynamic arrays in C?
Extremely common in not just C but all languages. C doesn’t have a built in dynamic array, so a lot of people roll their own. Other languages have it built in, like C#’s and Python’s List, C++’s std::vector, Java’s and Zig’s ArrayList, on and on. It’s a common data structure and language construct for a reason. If you don’t know size ahead of time, dynamic array can be a great choice. More on reddit.com
🌐 r/C_Programming
47
55
February 1, 2025
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
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
🌐
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 - ... Arrays in C are static in nature. It means that whenever you create an array in C with something like this ... It creates a memory block of five elements of size int on the stack.
🌐
Cplusplus
cplusplus.com › forum › beginner › 23308
Dynamic Array of Objects - C++ Forum
May 4, 2010 - When I try to use the .print() on a member of a dynamic array I get an error when I try to compile. Isn't a pointer to an object usable as an object and can use the dot (.) modifier to call member functions? This is the error I get when I try to compile. ... What I'd like to be able to is send the dynamic array though a for loop and print them all out. ... You should consider using the -> operator when working with pointers, rather than the . operator. It makes the intention a little more clear.
🌐
Florida State University
cs.fsu.edu › ~myers › cop3330 › notes › dma.html
Dynamic Allocation in Classes
For a dynamically created array, the pointer attaches to the starting position of the array, so can act as the array name: ... Just like basic types, objects can be allocated dynamically, as well.
🌐
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 - A dynamic array is an array that can automatically resize itself when its capacity is exceeded. This is achieved by allocating a new, larger block of memory, copying the existing elements from the old array, and freeing the old memory.
🌐
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.
Find elsewhere
🌐
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.
🌐
Codecademy
codecademy.com › docs › arrays › dynamic arrays
C | Arrays | Dynamic Arrays | Codecademy
January 30, 2025 - A dynamic array in C refers to an array whose size can be adjusted during runtime. Unlike static arrays, whose size must be fixed at compile time, dynamic arrays offer flexibility by utilizing memory allocation functions from the stdlib.h library, ...
🌐
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 ...
🌐
Scaler
scaler.com › home › topics › dynamic array in c
Dynamic Array in C - Scaler Topics
August 24, 2023 - They can be initialized with variable size, and their size can be modified later in the program. Dynamic arrays are allocated on the heap, whereas VLAs are allocated on the stack. It's important to note that, VLAs aren't the same as dynamic arrays. Some of the key differences are:-
🌐
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.
🌐
TutorialsPoint
tutorialspoint.com › cprogramming › c_dynamic_arrays.htm
Dynamic Arrays in C
In this chapter, we will explain in detail how dynamic arrays work in C programming. A dynamic array is a type of array which allocates memory at runtime, and its size can be changed later on in the program.
🌐
Reddit
reddit.com › r/c_programming › working with dynamic arrays in c
r/C_Programming on Reddit: Working with dynamic arrays in C
February 4, 2024 -

Hi there! How do C programmers work with dynamically allocated arrays – i.e vectors as in std::vector – in real C codebases, where dynamic allocations are possible (that is, there is heap memory and enough memory etc.)?

I keep finding myself wanting to do something like: struct vec { int* ptr; size_t len, cap; } and a bunch of other functions to create such a vector, push to it etc. If I were not to do this, I'd have to pass to many functions int** ptr, size_t* len, size_t* cap, which is very cumbersome.

None of the two methods above feel very C-like, given that there is no proper metaprogramming and that this approach seems like a too hefty abstraction for C but again, I don't have experience with real codebases, production code. In some situations I find that I can reduce the number of parameters, but not all.

What do you think? What is the solution? Do you have other approaches? Have you encountered this? If not, why?

Thank you very much for your input!

P.S. On mobile. If code formatting is broken, I'll fix it later. Also, the C23 changes which add some kind of generics using macros should not affect the answers here, as far as I can think; this question is in its essence concerned with abstraction in C and how it is approached in C.

Top answer
1 of 4
8
You’ll get a ton of different answers to this question because there is no standardized approach. The standardized approach arrived with C++ and std::vector. None of the two methods above feel very C-like […] You’ll see plenty of code like struct vec { int *data; size_t len, cap; }; This, at least, is clear and easy to understand. Any C programmer will look at this and immediately understand (or guess) that it’s a dynamic array. The only real question is how you work with it. Some people use macros. Either a bunch of macros to define all sorts of helper functions, or a small number of macros that you call directly. Some of these macros work on structures, some can work directly on variables stored anywhere. You can find examples in the Git codebase. Here’s one of them (line 1156): https://github.com/git/git/blob/2a540e432fe5dff3cfa9d3bf7ca56db2ad12ebb9/git-compat-util.h#L1156 Some people don’t use macros, and just use a small number of helper functions, or code that is copy-pasted. My advice? Keep it simple. Don’t go wild with the preprocessor. If you start doing lots of different tricks with the preprocessor, you can end up with C that is unreadable and hard to debug or analyze. Some amount of duplication is to be expected in a C codebase—use your own judgment, and try to keep your code simple.
2 of 4
6
Generally speaking, try to make the caller responsible for memory management. This allows them to use auto, static, or allocated storage as they like. Instead of forcing them to use allocated storage and the reallocating it, you can just fail and inform them of how much memory would be required to succeed. This is how the standard library operates, and snprintf is a reasonable example of the approach.
🌐
Phundrak
blog.phundrak.com › writing-dynamic-vector-c
[EN] Writing a Dynamic Array in C // Phundrak’s rambling
November 28, 2020 - When I wrote this library, I was mostly inspired by C++’s std::vector and Rust’s std::vec::Vec, but my library lacks some features both have: it’s still a simple one. Here is the list of what it is able to do: Create a dynamic array, with or without an initial capacity specified by the user
🌐
Medium
medium.com › @anthonybaxter819 › dynamic-array-in-c-a827b9cd56ef
Dynamic Arrays in C. Where Flexibility Meets Performance | by Anthony Baxter | Medium
July 9, 2025 - You could overestimate and allocate more space than necessary, but that would be a waste of memory with no guarantee that you still wouldn’t run out of room. What you really want is a flexible structure whose size grows with your needs; as you need more space, it allocates more. That’s a dynamic array.
Top answer
1 of 11
314

I can use pointers, but I am a bit afraid of using them.

If you need a dynamic array, you can't escape pointers. Why are you afraid though? They won't bite (as long as you're careful, that is). There's no built-in dynamic array in C, you'll just have to write one yourself. In C++, you can use the built-in std::vector class. C# and just about every other high-level language also have some similar class that manages dynamic arrays for you.

If you do plan to write your own, here's something to get you started: most dynamic array implementations work by starting off with an array of some (small) default size, then whenever you run out of space when adding a new element, double the size of the array. As you can see in the example below, it's not very difficult at all: (I've omitted safety checks for brevity)

typedef struct {
  int *array;
  size_t used;
  size_t size;
} Array;

void initArray(Array *a, size_t initialSize) {
  a->array = malloc(initialSize * sizeof(int));
  a->used = 0;
  a->size = initialSize;
}

void insertArray(Array *a, int element) {
  // a->used is the number of used entries, because a->array[a->used++] updates a->used only *after* the array has been accessed.
  // Therefore a->used can go up to a->size 
  if (a->used == a->size) {
    a->size *= 2;
    a->array = realloc(a->array, a->size * sizeof(int));
  }
  a->array[a->used++] = element;
}

void freeArray(Array *a) {
  free(a->array);
  a->array = NULL;
  a->used = a->size = 0;
}

Using it is just as simple:

Array a;
int i;

initArray(&a, 5);  // initially 5 elements
for (i = 0; i < 100; i++)
  insertArray(&a, i);  // automatically resizes as necessary
printf("%d\n", a.array[9]);  // print 10th element
printf("%d\n", a.used);  // print number of elements
freeArray(&a);
2 of 11
34

One simple solution involves mmap. This is great if you can tolerate a POSIX solution. Just map a whole page and guard against overflows, since realloc would fail for such values anyway. Modern OSes won't commit to the whole lot until you use it, and you can truncate files if you want.

Alternatively, there's realloc. As with everything that seems scarier at first than it was later, the best way to get over the initial fear is to immerse yourself into the discomfort of the unknown! It is at times like that which we learn the most, after all.

Unfortunately, there are limitations. While you're still learning to use a function, you shouldn't assume the role of a teacher, for example. I often read answers from those who seemingly don't know how to use realloc (i.e. the currently accepted answer!) telling others how to use it incorrectly, occasionally under the guise that they've omitted error handling, even though this is a common pitfall which needs mention. Here's an answer explaining how to use realloc correctly. Take note that the answer is storing the return value into a different variable in order to perform error checking.

Every time you call a function, and every time you use an array, you are using a pointer. The conversions are occurring implicitly, which if anything should be even scarier, as it's the things we don't see which often cause the most problems. For example, memory leaks...

Array operators are pointer operators. array[x] is really a shortcut for *(array + x), which can be broken down into: * and (array + x). It's most likely that the * is what confuses you. We can further eliminate the addition from the problem by assuming x to be 0, thus, array[0] becomes *array because adding 0 won't change the value...

... and thus we can see that *array is equivalent to array[0]. You can use one where you want to use the other, and vice versa. Array operators are pointer operators.

malloc, realloc and friends don't invent the concept of a pointer which you've been using all along; they merely use this to implement some other feature, which is a different form of storage duration, most suitable when you desire drastic, dynamic changes in size.

It is a shame that the currently accepted answer also goes against the grain of some other very well-founded advice on StackOverflow, and at the same time, misses an opportunity to introduce a little-known feature which shines for exactly this usecase: flexible array members! That's actually a pretty broken answer... :(

When you define your struct, declare your array at the end of the structure, without any upper bound. For example:

struct int_list {
    size_t size;
    int value[];
};

This will allow you to unite your array of int into the same allocation as your count, and having them bound like this can be very handy!

sizeof (struct int_list) will act as though value has a size of 0, so it'll tell you the size of the structure with an empty list. You still need to add to the size passed to realloc to specify the size of your list.

Another handy tip is to remember that realloc(NULL, x) is equivalent to malloc(x), and we can use this to simplify our code. For example:

int push_back(struct int_list **fubar, int value) {
    size_t x = *fubar ? fubar[0]->size : 0
         , y = x + 1;

    if ((x & y) == 0) {
        void *temp = realloc(*fubar, sizeof **fubar
                                   + (x + y) * sizeof fubar[0]->value[0]);
        if (!temp) { return 1; }
        *fubar = temp; // or, if you like, `fubar[0] = temp;`
    }

    fubar[0]->value[x] = value;
    fubar[0]->size = y;
    return 0;
}

struct int_list *array = NULL;

The reason I chose to use struct int_list ** as the first argument may not seem immediately obvious, but if you think about the second argument, any changes made to value from within push_back would not be visible to the function we're calling from, right? The same goes for the first argument, and we need to be able to modify our array, not just here but possibly also in any other function/s we pass it to...

array starts off pointing at nothing; it is an empty list. Initialising it is the same as adding to it. For example:

struct int_list *array = NULL;
if (!push_back(&array, 42)) {
    // success!
}

P.S. Remember to free(array); when you're done with it!

🌐
Bytesbeneath
bytesbeneath.com › p › dynamic-arrays-in-c
Dynamic Arrays in C - by Dylan Falconer - Bytes Beneath
January 18, 2024 - You could have the allocator provide a realloc function so you dont have to handle the realloc logic in `array_ensure_capacity`. Would make it easy to provide the C stdlib realloc function instead of handling the logic here. All that logic could be boiled down to just this: const size_t new_size = sizeof(ListPrelude) + new_capacity * item_size; prelude = prelude->allocator->realloc(prelude, new_size); ... This article has been very educational thus far on how one could manage dynamic arrays in c.