代码适用于较小的输入,但不适用于大型输入为什么?

问题描述

给定一个由 m * n 个元素(m 行,n 列)组成的矩阵,按螺旋顺序返回矩阵的所有元素。为什么它适用于较小的输入而不适用于较大的输入?而同样的代码也适用于其他系统。下面给出了我使用的输入和输出

#include<iostream>
using namespace std;
int main(){

    int n,m;
    cin>>n>>m;

    int a[n][m];

    for (int i = 0; i < n; i++)
    {
        for (int j = 0; j < n; j++)
            cin>>a[i][j];   
    }
    
    // spiral order print

    int row_start = 0,row_end = n-1,column_start = 0,column_end = m-1;
    while (row_start <= row_end && column_start <= column_end)
    {
        //for row start
        for (int col = column_start; col <= column_end; coL++)
        {
            cout<<a[row_start][col]<<" ";
        }
        row_start++;

        //for column end
        for (int row = row_start; row <= row_end; row++)
        {
            cout<<a[row][column_end]<<" ";
        }
        column_end--;

        //for row end
        for (int col = column_end; col >= column_start; col--)
        {
            cout<<a[row_end][col]<<" ";
        }
        row_end--;

        //for column start
        for (int row = row_end; row >= row_start; row--)
        {
            cout<<a[row][column_start]<<" ";
        }
        column_start++;
    }
    
return 0;
}

输入:

5 6
1 5 7 9 10 11
6 10 12 13 20 21
9 25 29 30 32 41
15 55 59 63 68 70
40 70 79 81 95 105

输出

1 5 7 9 10 1878030368 -1 -1 6422096 4200108 40 70 68 63 59 30 20 11 6 10 12 13 29 55 15 41 32 21 9 25 9

解决方法

检查您的代码:

for (int i = 0; i < n; i++)
{
    for (int j = 0; j < n; j++)
        cin>>a[i][j];   
}

第二个条件应该是:j < m

我猜你的代码正在访问垃圾内存。