I thought that the following code would work. However, it is printing the first row and then throwing a segmentation fault.
const unsigned **grid = new const unsigned*[10]{new const unsigned[10]{0}};
for (int r = 0; r < 10; r )
{
for (int c = 0; c < 10; c )
{
std::cout << grid[r][c] << " ";
}
std::cout << std::endl;
}
Does anyone know what I am (probably naively) doing incorrectly?
CodePudding user response:
Here are some options using dynamic allocation (of course it is simpler to use automatic allocation):
// should be delete[]'d at some point in future
auto* arr1 = new const unsigned[10][10]{};
// #include <memory>, C 14
auto arr2 = std::make_unique<const unsigned[][10]>(10);
// #include <vector>
auto const arr3 = std::vector<unsigned>(100); // use index math
// #include <array>
using A10 = std::array<unsigned, 10>;
auto const arr4 = std::vector< A10 >(10, A10{});
CodePudding user response:
So here is a solution that should work with every compiler:
const unsigned **grid = new const unsigned*[10]{new const unsigned[10]{0},
new const unsigned[10]{0}, new const unsigned[10]{0}, new const unsigned[10]{0},
new const unsigned[10]{0}, new const unsigned[10]{0}, new const unsigned[10]{0},
new const unsigned[10]{0}, new const unsigned[10]{0}, new const unsigned[10]{0} };
for (int r = 0; r < 10; r ){
for (int c = 0; c < 10; c )
{
std::cout << grid[r][c] << " ";
}
std::cout << std::endl;
}
To be honest I am not understanding why the grid
should be const
.
CodePudding user response:
Here's how to properly handle 2D dynamic arrays. I'll remove const for now since it's most important that you handle dynamic memory properly:
#include <iostream>
int main() {
unsigned** grid = new unsigned* [10];
for (int i = 0; i < 10; i) {
grid[i] = new unsigned[10];
}
for (int r = 0; r < 10; r )
{
for (int c = 0; c < 10; c )
{
std::cout << grid[r][c] << " ";
}
std::cout << std::endl;
}
for (int i = 0; i < 10; i) {
delete[] grid[i];
}
delete[] grid;
return 0;
}
Don't forget to delete[] your arrays allocated with new, and make sure you know the difference between "delete" and "delete[]"
As for the people who always decry writing code like this, this is a necessary step for anyone learning C and memory management. A plain example with raw pointers can only help.