0

I want dynamically define an array b in input() I'm trying like this where int size=9;

int b*=new int[size][size]

But getting many error while compiling

Thank you for any guidance
Regards

Edited by vishalonne

2
Contributors
1
Reply
2
Views
4 Years
Discussion Span
Last Post by deceptikon
0

2D arrays aren't a single entity like in some languages, they're arrays of arrays. What you're actually trying to allocate here is a pointer to size arrays of size int, and the destination type needs to reflect that:

int (*b)[size] = new int[size][size];

This is assuming size is a const variable or macro, otherwise you're trying to do something that's not legal in standard C++: define an array with a size that isn't a compile time constant.

I'm going to go out on a limb and assume that what you really want is a fully dynamic simulated 2D array, in which case you should either use the std::vector class or follow this pattern for allocation:

int **b = new int*[size];

for (int i = 0; i < size; ++i)
    b[i] = new int[size];

And this one for release:

for (int i = 0; i < size; ++i)
    delete[] b[i];
delete[] b;

But std::vector is strongly recommended unless you're just trying to learn how pointers and dynamic memory work.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.