0

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?

1
  • Hi there, please provide an minimal reproducible example that clearly shows the issue. How are you calling the function? What parameters/array are you passing into it? What is your overarching goal? "Adding a 2D array to a 1D array" is ambiguous since it could be done in different ways. Please edit your question and elaborate. Thanks. Commented Mar 1, 2019 at 16:27

1 Answer 1

1

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.