简体   繁体   中英

Creating a 2D Array using dynamic memory allocation in C++

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[i + 1]; //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.

The program has undefined behavior.

In this for loop

for (int i = 0; i < r; i++) 
{ 
    p[i] = new int[i + 1]; //this line here is the marked line
} 

in each "row" of the array you allocated i + 1 elements. But in the next for loop

for (int i = 0; i < r; i++) 
{ 
    for (int j = 0;j <c; j++) 
    { cin >> p[i][j]; 
    } 
}

you are trying to access c elements in each row independent on how many elements actually were allocated.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM