简体   繁体   中英

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?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM