c++arrayspointersg++coredump

C++ pointer of pointers to arrays


I have a bit of a problem with creating an array of arrays, or an array of pointers to arrays to be more precise, I seem to have eliminated all errors because the program compiles just fine (I'm using g++) however when I try to run it it gives a "core dumped" message.

This is my code?

#include<iostream>
#include<ctime>
#include<cstdlib>

using namespace std;

void create_array(int **pp)
    {
        pp = new int*[4];
        for (int i = 0; i<4; i++)
        {
            pp[i] = new int[4];
        }
    }

int main()
    {
        srand(time(NULL));
        int **pp;
        create_array(pp);

        for (int x = 0; x<4; x++)
        {
            for(int y = 0; y<4; y++)
            {
                pp[x][y] = rand()%9;
            }
        }
        cout << pp[3][2] << endl;
        return 0;
    }

Solution

  •  void create_array(int **pp)
    {
        pp = new int*[4];
        for (int i = 0; i<4; i++)
        {
            pp[i] = new int[4];
        }
    }
    

    pp is an array of pointers to int, however, it is passed by value. so the original caller pp in main is not affected. pp inside main remain uninitialized after you call the create_array function. When you try to assign value to it. it will result in core dump.

    try to use vector <vector<int>> instead in C++.

    Or try:

    void create_array(int **&pp)
    {                     //^^
        pp = new int*[4];
        for (int i = 0; i<4; i++)
        {
            pp[i] = new int[4];
        }
    }
    

    with the above change, it outputs the following if you try to print the whole matrix on my machine:

     8 7 6 3
     3 5 6 4
     3 8 7 6
     0 0 5 8