My stack knowledge is very rudimentary compared to a bunch, but when it comes to arrays, from what I know, something like this is created on the stack
float x[100];
while something like this is created on the heap
float* x = new float[100];
But what happens if I create a class of an array of templates and pass it to an array of type "stack" (for example, float[100] )? Example:
#include <iostream> using namespace std; template <class T> class Array { public: int size; T* data; Array(int size_) : size(size_) { data = new T[size]; } ~Array() { delete [] data; } }; int main() { int m = 1000000; const int n = 100; Array<float[n]>* array = new Array<float[n]>(m); for (int i = 0; i < m; i++) for (int j = 0; j < n; j++) array->data[i][j] = i * j; cout << array->data[10][9] << endl; delete array; }
What exactly is going on here? Is this memory created on the stack or on the heap? My guess is a bunch, but how does it work? Does the compiler allocate one large block of memory and then store pointers that index each element of n into it? Or does it allocate many smaller blocks of memory (not necessarily contiguous) and store pointers to each block?
Also, I cannot do this without the help of a template. In particular, this code does not compile:
int m = 1000; const int n = 100; (float[n])* array = new (float[n])[m];
What's going on here?
EDIT:
Thanks for the syntax advice, everyone. I was really interested in what is happening in the block
int m = 1000; const int n = 100; float (*array)[n] = new float[m][n];
but I did not know how to write it without using templates. The only thing that really interested me was that the compiler allocates this as one big block on the heap, how can you use the array[i][j] syntax to access a specific element without saving pointers to every nth element? Then I realized that since n constant, sizeof(float[n]) fixed, so when you create an array, the compiler allocates an array of elements m , where each element is float[n] , which in my case is 100 * 4 = 400 bytes. Now everything makes sense. Thanks!