0

I want to memset a 2D array to 0. Here's my code.. But it always giving me seg fault;

      bool **visited=new bool*[m];
         for(int i=0;i<m;++i)
           visited[i] = new bool[m];

I have tried memset(visited, 0, sizeof(visited[0][0]) * m * m); and memset(visited, 0, sizeof visited); , But nonw of this works and gives me segfault. how do I do that?

David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
Tamim Addari
  • 7,591
  • 9
  • 40
  • 59

1 Answers1

7

Your array is not contiguous since it is not actually a multi-dimensional array. It's an array of arrays, sometimes known as a jagged array.

So, your rows can, and will, be disjoint. Hence you'll need to call memset on each row.

bool **visited=new bool*[m];
for(int i=0;i<m;++i)
{
    visited[i] = new bool[m];
    memset(visited[i], 0, sizeof(visited[i][0]) * m);
}

Although, I can't refrain from pointing out that you should probably be using C++ features rather than writing what appears to be C with the use of the new operator.

David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490