[英]Adding 2d Array to 1d Array
The code is supposed to create a 2d array fill it with some values then put the values into 1d array and add **I have this function called AddTab that should add the 2d array to 1d array. 代码应该创建一个2d数组,并用一些值填充它,然后将值放入1d数组并添加**我有一个称为AddTab的函数,该函数应将2d数组添加到1d数组中。
#include "pch.h"
#include <iostream>
using namespace std;
int **createTab(int n, int m)
{
int **tab = nullptr;
try {
tab = new int *[n];
}
catch (bad_alloc)
{
cout << "error";
exit(0);
}
for (int i = 0; i < n; i++)
{
try {
tab[i] = new int[m] {};
}
catch (bad_alloc)
{
cout << "error";
exit(0);
}
}
return tab;
}
void FillTab(int m, int n, int **tab)
{
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
cin >> tab[i][j];
}
}
}
void AddTab(int **tab,int n,int m)
{
int *temp_tab=new int[m];
memset(temp_tab, 0, sizeof(temp_tab));
for (int i=0;i<m;i++)
{
for (int j=0;j<n;j++)
{
temp_tab[j] += tab[i][j];
cout << temp_tab[j] << "( " << j << ")" << endl;
}
}
}
int main()
{
int **X = nullptr;
X = createTab(3, 3);
FillTab(3, 3, X);
AddTab(X, 3, 3);
}
I filled the 3x3 2d tab with 1's. 我用1填充了3x3 2d标签。
For the first loop it was supposed to be {1,1,1} but instead something weird pops up. 对于第一个循环,它应该是{1,1,1},但是会弹出一些奇怪的东西。
1( 0)
-842150450( 1)
-842150450( 2)
2( 0)
-842150449( 1)
-842150449( 2)
3( 0)
-842150448( 1)
-842150448( 2)
What can I do so it will work fine? 我该怎么办才能正常工作?
sizeof(temp_tab)
for 对于
int *temp_tab
returns 4/8 bytes, it depends on system. 返回4/8字节,取决于系统。 So only first 4/8 bytes are set to 0 for your dynamic allocated array. 因此,动态分配数组仅将前4/8个字节设置为0。 If temp_tab[j]
is not set to 0, by doing temp_tab[j] += tab[i][j];
如果temp_tab[j]
未设置为0,则通过执行temp_tab[j] += tab[i][j];
you update garbage value and finally as result you get garbage value as well. 您更新了垃圾值,最后,您也获得了垃圾值。
Fix: 固定:
memset(temp_tab, 0, sizeof(int) * m);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.