Search code examples
c++arrayspointerssrand

C++ - Initializing a 2D array with pointer notation


I'm working on 2D array in C++. I'm having trouble connecting the concepts of arrays and pointers. I know that they are related in terms of memory allocation and accessing elements. For example

int *arr;
int num = arr + 1*sizeof(int);

is the same as

int arr[];
int num = arr[1];

I'm trying to find the same connection between 2D arrays and pointers Here's my code

void printGrid(int **arr) {
 for (int i = 0; i < 10; i++) {
  for (int j = 0; j < 10; j++) {
   cout << setw(3);
   cout << arr[i][j] << " ";
  }
  cout << endl;
 }
}

int main() {
 int **grid;
 srand(time(NULL));
 for (int i = 0; i < 10; i++) {
  for (int j = 0; j < 10; j++) {
   grid[i][j] = rand() % 11;
  }
 }
 printGrid(grid);
}

When I compile this, it compiles. When I then try to run it, I get a segfault. Could someone please point out the error in my code?

Thanks SO


Solution

  • int **grid;
     srand(time(NULL));
     for (int i = 0; i < 10; i++) {
      for (int j = 0; j < 10; j++) {
       grid[i][j] = rand() % 11;
      }
     }
    

    Where is the part which should allocate memory for the dynamic array? And possibly also for its elements? To remedy this you could have done

    // Allocating memory for array and elements
    int **grid = new int*[10];
    for (int i = 0; i < 10; i++) {
      grid[i] = new int[10];
    }
    // Now fill the array as you had in your code
    //
    ...
    // Deletion part
    for (int i = 0; i < 10; i++) {
      delete[] grid[i];
    }
    delete[] grid;
    

    Also,

    I'm working on 2D array in C++. I'm having trouble connecting the concepts of arrays and pointers. I know that they are related in terms of memory allocation and accessing elements. For example

    int *arr; int num = arr + 1*sizeof(int);

    is the same as

    int arr[]; int num = arr[1];

    No they are not the same. This would be same though:

    int x[] = {0, 2, 3};
    int *arr = x;
    int num = *(arr + 1); //Look up pointer arithmetic; same as num=arr[1];