1

I am Java programmer. I'm trying to fill array in Win32 project

int **Data::matrixInitialize()
{
    int** MX = new int*[n];
    for (int i = 0; i < n; i++)
    {
        for (int j = 0; j < n; j++)
        {
            MX[i][j] = 1;
        }
    }
    return MX;
}

But this code throw an exeption. Please help me to fill 2D array.

AskQuestion
  • 346
  • 4
  • 18
  • What exception are you getting? – drum Oct 27 '14 at 19:29
  • 1
    Do you have to use arrays? I would strongly recommend using `vector>` or at least `array>` instead of raw arrays. – Cory Kramer Oct 27 '14 at 19:30
  • 2
    Your new only creates an array of pointers. You still need to allocate the integers themselves (more new). Better to use vector anyway. – Niall Oct 27 '14 at 19:31

2 Answers2

4

You miss an allocation:

int **Data::matrixInitialize()
{
    int** MX = new int*[n];
    for (int i = 0; i < n; i++)
    {
        MX[i] = new int[n]; // Missing line
        for (int j = 0; j < n; j++)
        {
            MX[i][j] = 1;
        }
    }
    return MX;
}

but it would be better to use std::vector or std::array.

Jarod42
  • 203,559
  • 14
  • 181
  • 302
1

Try the following

#include <algorithm>

//...

int **Data::matrixInitialize()
{
    int** MX = new int*[n];

    for ( int i = 0; i < n; i++ )
    {
        MX[i] = new int[n];
        std::fill_n( MX[i], n, 1 );
    }

    return MX;
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335