2

I need to efficiently allocate an array of two dimensions, one being known (5) and the other being unknown.

My aim is to have a continuous block of memory named block that stores my data in the following way : block[0,0] block[0,1] block[0,2] block[0,3] block[0,4] block[1,0] ...]

The following code compiles (in C++) :

unsigned int size2=200;
auto block = new float[size2][5];

Is it correct ? What is the type of the variable block ? I have tried :

float[5]* block = new float[size2][5];
float[5] block[] = new float[size2][5];
float block[][5] = new float[size2][5];
float block*[5] = new float[size2][5];

All of them leads to an error. I am running out of imagination...

YSC
  • 38,212
  • 9
  • 96
  • 149

3 Answers3

3
unsigned int size2=200;
auto block = new float[size2][5];

Is it correct?

Yes it is correct.

What is the type of the variable block?

Using auto here is the best you can do. But for learning purpose, the type of block is float(*)[5]. To define a variable with that type, you must use the following syntax:

unsigned int size2=200;
float(*block)[5] = new float[size2][5];

Demo: https://godbolt.org/z/4iJMA5


"How can I read such a thing as float(*block)[5]?" you might ask. It's simple, use the C++ Guru Snail Rule.

YSC
  • 38,212
  • 9
  • 96
  • 149
  • You can do something similar defining a `typedef` allowing a somewhat more natural *pointer to array* allocation, e.g. `typedef float row_t[5]; ... row_t *block = new row_t[200];` (whether that is more clear or not is arguable) – David C. Rankin Nov 14 '18 at 17:54
2
unsigned int size2=200;
auto block = new float[size2][5];

Is it correct ?

Yes, although a bare owning pointer is a bad idea. It's better to use std::vector for dynamic arrays.

What is the type of the variable block ?

It is float (*)[5] i.e. pointer to an array of 5 float.


As I mentioned, I recommend using std::vector instead to avoid pitfalls with memory management:

std::vector<std::array<float, 5>> block(size2);
Community
  • 1
  • 1
eerorika
  • 232,697
  • 12
  • 197
  • 326
1

I'm a bit old-school, but the simplest is really

new float[size2 * 5];

and access it with

my_array[y * 5 + x]

You can even add an inline helper function

int at(int x, int y) { return y * 5 + x;}

...

my_array[at(x,y)]

And ideally combine with a std::vector instead of a dynamic array.

Jeffrey
  • 11,063
  • 1
  • 21
  • 42
  • I don't see how this is better than the questioner's own version tbh. Using this is more complicated. – Galik Nov 14 '18 at 17:21