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
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
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.
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.