I am trying to implement a 2D array using dynamic memory allocation. Here is my code:
#include <iostream>
using namespace std;
int main()
{
int r, c;
cin >> r >> c;
int** p = new int*[r];
for (int i = 0; i < r; i++)
{
p[i] = new int[c]; //this line here is the marked line
}
for (int i = 0; i < r; i++)
{
for (int j = 0;j <c; j++)
{ cin >> p[i][j];
}
}
for (int i = 0; i < r; i++)
{
for (int j = 0;j <c; j++)
{
cout << p[i][j]<<" ";
}
}
cout<<"\n";
for (int i = 0; i < r; i++)
{
delete [] p[i];
}
delete [] p;
return 0;
}
I then compiled the same code by commenting the marked line in different compilers.
VS Code with MinGW (MinGW.org GCC-6.3.0-1) -> Compiled successfully with all the wanted output.
Jdoodle and other online compilers (tried in both c++14 and c++17 latest versions) -> The program gives segmentation fault after reading the second input for array element (reads the r, c and first 2 input for the array succesfully).
Could someone please explain, IN VS CODE, how am I getting the correct output? Which memory, heap or stack is used if marked line is commented? What are the differences when the marked line is commented and when not commented? And what's the reason of Segmentation fault? Thanks.