在C++中添加两个 2D 数组 - 为什么这个程序崩溃
Adding two 2D arrays together in C++ - Why do this program crash?
嘿,我是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;
}
相关文章:
- 数组长度,为什么从命令行获取时不能使用它?
- 当我在main中声明了我的2d数组时,为什么我的程序会退出
- 为什么我不能将 rand() 与数组的大小一起使用?
- 在C++中传递给函数时,为什么要指定数组大小作为参数
- 为什么我的排序算法会更改数组值
- 为什么std::vector比数组慢
- 为什么调用堆栈数组会导致内存泄漏
- 为什么用结构初始化数组需要指定结构名称
- 为什么我需要C++中不同的排序格式来对这个USACO代码上的数组和优先级队列进行排序
- 为什么可以修改数组 b?
- 为什么我们将单个或多维数组的大小声明为常量值?
- 为什么我的数组双精度函数不起作用?
- 为什么 2 个相同数组的元素彼此相等
- 为什么 &a 和 c++ 中的静态数组相同?
- 初始化不可移动对象数组:为什么这样的代码无法在 GCC 上编译?
- C++ 结构数组 - 为什么它必须是指针
- 在C++中添加两个 2D 数组 - 为什么这个程序崩溃
- 动态分配缓冲空间为二维数组 - 为什么失败
- 非恒定大小的数组:为什么这甚至可以工作
- C++字符数组——为什么是垃圾