Search code examples
c++arraysmemset

memset on 2d array of chars


With an 2D array of ints, everything is fine:

 int **p = new int*[8];
 for (int i = 0; i < 8; i++)
    p[i] = new int[8];
 memset(p, 0, 64 * sizeof(int))

But with 2D array of chars, I get a runtime error

 char **p = new char*[8];
 for (int i = 0; i < 8; i++)
     p[i] = new char[8];
 memset(p, 0, 64 * sizeof(char));

What is wrong with my code?


Solution

  • I think both might be wrong and only the second one is failing at runtime. Anytime you allocate an array with new it goes on the heap and it returns a pointer. So in your case you have 8 pointers of type X storied in p. You do not have an 8x8 continuous block of memory but rather 8 pointers to 8 blocks of memory, all of size 8*sizeof(X).

    The solution is to call memset for each element in p or to allocate one block of memory and use index math to emulate multidimensional access or some other trick I am probably missing.