简体   繁体   中英

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.

    #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.

For the first loop it was supposed to be {1,1,1} but instead something weird pops up.

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. So only first 4/8 bytes are set to 0 for your dynamic allocated array. If temp_tab[j] is not set to 0, by doing 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM