Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use memset or fill_n to initialize a dynamic two dimensional array in C++

I have a 2D array created dynamically.

int **abc = new int*[rows];

for (uint32_t i = 0; i < rows; i++)
{
    abc[i] = new int[cols];
}

I want to fill the array with some value (say 1). I can loop over each item and do it.

But is there a simpler way. I am trying to use memset and std::fill_n as mentioned in this post.

std::fill_n(abc, rows * cols, 1);
memset(abc, 1, rows * cols * sizeof(int));

Using memset crashes my program. Using fill_n gives a compile error.

invalid conversion from 'int' to 'int*' [-fpermissive]

What am I doing wrong here ?

like image 845
SyncMaster Avatar asked Apr 08 '16 18:04

SyncMaster


1 Answers

You could just use vector:

std::vector<std::vector<int>> abc(rows, std::vector<int>(cols, 1));

You cannot use std::fill_n or memset on abc directly, it simply will not work. You can only use either on the sub-arrays:

int **abc = new int*[rows];

for (uint32_t i = 0; i < rows; i++)
{
    abc[i] = new int[cols];
    std::fill_n(abc[i], cols, 1);
}

Or make the whole thing single-dimensional:

int *abc = new int[rows * cols];
std::fill_n(abc, rows*cols, 1);

Or I guess you could use std::generate_n in combination with std::fill_n, but this just seems confusing:

int **abc = new int*[rows];
std::generate_n(abc, rows, [cols]{
    int* row = new int[cols];
    std::fill_n(row, cols, 1);
    return row;
});
like image 124
Barry Avatar answered Oct 15 '22 14:10

Barry