打印二维数组后C ++崩溃

时间:2018-11-18 16:00:47

标签: c++ matrix multidimensional-array crash

打印二维数组后,我的程序崩溃了,我也不知道为什么。程序在打印“ test2”之前崩溃:

//initialising
int** matrix = new int*[x * y];
for (int i = 0; i < x; i++){
    matrix[i] = new int[y];
}
//filling with 0
for (int row = 0; row < x; row++){
     for (int cols = 0; cols < y; cols++){
          matrix [row][cols] = 0;
     }
}
//printing
for(int i = 0; i < x; ++i) {
    for(int j = 0; j < y; ++j){
       std::cout << (matrix[i][j]) << ", ";
    }
    std::cout << std::endl;
}

std::cout << "test2" << std::endl;

1 个答案:

答案 0 :(得分:1)

 #include<iostream>

 void func(int x, int y)
 {
    // initialising
    int **matrix = new int *[x];
    for (int i = 0; i < x; i++)
    {
        matrix[i] = new int[y];
    }
// filling with 0
    for (int row = 0; row < x; row++)
    {
        for (int cols = 0; cols < y; cols++)
    {
        matrix[row][cols] = 0;
    }
}
// printing
for (int i = 0; i < (x); ++i)
{
    for (int j = 0; j < (y); ++j)
    {
        std::cout << (matrix[i][j]) << ", ";
    }
    std::cout << std::endl;
}

std::cout << "test2" << std::endl;

    for(int i = 0; i < x; i++)
          delete[]matrix[i]; // clean up each y

delete[]matrix;  // clean up x
 }

 int main()
 {
    func(5, 5);
 } 

您的x数组仅需为x长。您的每个x指针都指向一个y长的数组。调用new []时,必须在new []分配的每个指针上调用delete []以防止内存泄漏。这是代码https://ideone.com/UL2IJn

的验证