-5

I'm new to C++, and I've been trying to figure out how to access just 1 element in a 2D array that I've dynamically allocated like so:

char** array;
array = new char*[3];
for(int i = 0; i < 3; i++) {
    array[i] = new char [3];
}

I've been trying to access it like this:

cout<< array[0][0];

Whenever I try to do this, nothing prints out and the program segfaults. How should I fix it so that it prints? Thank you for your time!

prestococo
  • 15
  • 2
  • 7

1 Answers1

0

If you're looking to create a 2D array you should take a look at this Stack Overflow post here. It has a nice image to explain how 2D memory is laid out and how to properly create the array. Remember, when you create dynamic memory using new you need to delete the memory manually with delete[]. The second response gives a code example of how to delete the 2D array. Once you have your array you can access it by cout << array[x][y], where x and y are your row and column indices. I'd focus on properly creating the 2D array and understanding that first.

Community
  • 1
  • 1
user2205930
  • 1,046
  • 12
  • 26