0

I have this function meant to initialize a multidimensional 2d (6x6) array to zero. I call the function in main using cout to test it and it outputs garbage. Please help. Thanks!

int** initializeArray(void)
{
    typedef int* rollArray;     //this line is actually outside of the function in my
                                //program
int i, j;
rollArray *m = new rollArray[6];

for (i = 0; i < 6; i++)
    m[i] = new int[6];

for (i = 0; i < 6; i++)
    for (j = 0; j < 6; j++)
        m[i][j] = 0;

return m;
}
3
  • Fix your code indentation please Commented Jul 18, 2013 at 23:19
  • You are initializing a one dimensional array... Commented Jul 18, 2013 at 23:20
  • 2
    Include your test code that outputs garbage. Commented Jul 18, 2013 at 23:20

2 Answers 2

1

If the value 6 is known at compile-time, I would suggest using std::array in a nested fashion. For example:

#include <array>
#include <iostream>

int main()
{
    std::array<std::array<int,6>,6> a = {0};

    for (int i = 0; i < 6; ++i)
    {
        for (int j = 0; j < 6; ++j)
        {
            std::cout << a[i][j] << std::endl; // Prints 0.
        }
    }

    return 0;
}

In fact, you won't even need to create a function to initialize your array. Declare your nested array and you are good to go. (If you don't know the dimension at compile-time, you could use std::vector in a similar fashion.)

Sign up to request clarification or add additional context in comments.

3 Comments

Even better, you can use ranged-for loops to print it.
True...how much C++11 should we introduce at once? :)
As much as is needed to write safer or more readable code imo.
0

The problem is with your test.
How can you mess up such a simple test? Just use:

int ** a = initializeArray();
int i,j;
for (i = 0; i < 6; i++) {
    for (j = 0; j < 6; j++) {
        cout << a[i][j] << " "; 
    }
    cout << endl;
}

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.