-1

How do you initialize the value of x using array new:

int (*x)[5] = ?

new int[5] doesn't work because it has a type of int*

Do you have to use a C-style cast as follows?

int (*x)[5] = (int( *)[5])(new int[5]);
Barmar
  • 741,623
  • 53
  • 500
  • 612
blay
  • 1
  • 1
  • 1
    Are you using an array instead of std:vector because of some constraint of your project? – Jorge Y. Feb 10 '18 at 09:44
  • do you mean how to create array of pointers dynamically ? – mightyWOZ Feb 10 '18 at 09:45
  • You understand `int (*x)[5];` declares a pointer to array of 5 `int`? It needs the address of a valid array of 5-ints, or can serve as the pointer to multiple arrays of 5 ints. – David C. Rankin Feb 10 '18 at 09:48
  • Possible duplicate of [Preventing array decay when allocating memory on the heap?](https://stackoverflow.com/questions/48494479/preventing-array-decay-when-allocating-memory-on-the-heap) – xskxzr Feb 10 '18 at 12:26

2 Answers2

5

A fixed sized array in C++ would be std::array.

And, guessing from the pointer to array int (*x)[5] this might be either

std::array<int, 5> x;

or

std::array<int, 5> *x = new std::array<int, 5>;

Although the former is preferred, unless there's a real need to put the array on the heap.


If you want a variable number of fixed sized arrays, combine this with a std::vector

std::vector<std::array<int, 5> > x;
Olaf Dietsche
  • 72,253
  • 8
  • 102
  • 198
1

This works

typedef int int5[5];

int main()
{
    int (*x)[5] = new int5[1];
    return 0;
}

There may be a way to do it without a typedef, but I didn't investigate too much.

UPDATE

Somewhat counter intuitively this is also correct

int (*x)[5] = new int[1][5];

And no you shouldn't use a cast, casts are rarely the right solution, especially for beginners.

john
  • 85,011
  • 4
  • 57
  • 81