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.

3
  • What exception are you getting?
    – drum
    Commented Oct 27, 2014 at 19:29
  • 1
    Do you have to use arrays? I would strongly recommend using vector<vector<int>> or at least array<array<int>> instead of raw arrays. Commented Oct 27, 2014 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
    Commented Oct 27, 2014 at 19:31

2 Answers 2

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.

0
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;
}

Not the answer you're looking for? Browse other questions tagged or ask your own question.