TheHorse
TheHorse

Reputation: 2797

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?

Upvotes: 1

Views: 2040

Answers (2)

Andre Luiz Vieira
Andre Luiz Vieira

Reputation: 11

This would work if your array had not been dynamically allocated:

memset(p, 0, 8 * 8 * sizeof(char[0][0]));

Note that now it is being passed the size of an element of the array to sizeof.

But in your case the solution is indeed to call memset for each element in p:

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

As said before, another solution is to transform p in a 1D array.

Upvotes: 0

Andrew White
Andrew White

Reputation: 53486

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.

Upvotes: 7

Related Questions