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?

3
  • If you are using STL you should try using vector<bool> instead of array of booleans. en.cppreference.com/w/cpp/container/vector_bool
    – TomF
    Aug 23, 2013 at 20:13
  • If m is known, then use bitset instead.
    – xis
    Aug 23, 2013 at 20:14
  • You don't have a 2D array. You have a pointer to a pointer. Aug 23, 2013 at 21:10

1 Answer 1

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.

3

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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