在C++中添加两个 2D 数组 - 为什么这个程序崩溃

Adding two 2D arrays together in C++ - Why do this program crash?

本文关键字:数组 为什么 崩溃 程序 2D C++ 添加 两个      更新时间:2023-10-16

嘿,我是C++编程的初学者。我制作了一个程序,旨在将两个 2D 数组加在一起。但是,程序输出值,直到程序崩溃。有人可以帮助我确定问题吗?

#include <iostream>
using namespace std;
int main(int argc, char** argv)
{
    int a[10][10], c[10][10], i, j;
    for (i = 1; i <= 10; ++i)
    {
        for(j=0; j < 10; ++j)
        {
            a[i][j] = i * j; 
        }
    }
    // We are able to treat the individual columns as arrays
    for (int i = 0; i < 10; ++i)
    {
        int *b = a[i];
        for (int j = 0; j < 10; ++j)
        {
            cout << b[j] << " ";
        }
        cout << endl;
    }
    cout << "****" << endl;
    // Declare a multidimensional array on the heap
    int **b = new int*[10];
    // need to allocate all members individually
    for (int i = 0; i < 10; ++i)
    {
        b[i] = new int[10];
    }
    // Set the values of b
    for (int i = 0; i < 10; ++i)
    {
        for (j = 0; j < 10; ++j)
        {
            b[i][j] = (i * 10) + j; 
        }
    }
    for (i = 0; i < 10; ++i)
    {
        for (j = 1; j <= 10; ++j)
        {
            c[i][j] = a[i][j] + b[i][j];
        }
    }
    for (i = 0; i < 10; ++i)
    {
        for (j = 1; j <= 10; ++j)
        {
            cout << c[i][j] << endl; 
        }
    }
    // Delete the multidimensional array - have to delete each part 
    for (int i = 0; i < 10; ++i)
    {
        delete[] b[i];
    }
    delete[] b;
    return 0; 
}

我纠正了你的代码。现在,它正在工作并且程序没有崩溃。你可以试试。

#include<conio.h>
#include<iostream.h>
int main(int argc, char** argv)
{
    int a[10][10], c[10][10], i, j;
    for (i = 0; i <10; ++i)
    {
        for(j=0; j < 10; ++j)
        {
            a[i][j] = i * j;
        }
    }
    //We are able to treat the individual columns as arrays;
    for (i = 0; i < 10; ++i)
    {
        int *b = a[i];
        for (int j = 0; j < 10; ++j)
        {
            cout << b[j] << " ";
        }
        cout << endl;
    }
    cout << "****" << endl;
    //Declare a multidimensional array on the heap;
    int **b = new int*[10];
    //need to allocate all members individually
    for (i = 0; i < 10; ++i)
    {
        b[i] = new int[10];
    }
    //Set the values of b
    for ( i = 0; i < 10; ++i)
    {
       for (j = 0; j < 10; ++j)
       {
           b[i][j] = (i * 10) + j;
       }
    }
    for (i = 0; i < 10; ++i)
    {
        for (j = 0; j <10; ++j)
        {
            c[i][j] = a[i][j] + b[i][j];
        }
    }
    for (i = 0; i < 10; ++i)
    {
        for (j = 0;j < 10; ++j)
        {
            cout << c[i][j] << " ";
        }
        cout<<endl;
    }
//  Delete the multidimensional array - have to delete each part
    for (i = 0; i < 10; ++i)
    {
        delete[] b[i];
    }
    delete[] b;
    return 0;
}