Can I use memset to initialize a 2 dimensional array?

Viewed 361

According to the C standard (SO link 1 and link 2) we cannot access an element of a row using out-of-bounds index:

int x[10][10] = ...; // initialize x
int q = x[0][10]; // This is an out-of-bounds access

Then is it valid to initialize the array using the following loop?

int *p = &x[0][0];
for (int i = 0; i < 100; ++i)
  p[i] = 0;

If this is not valid, then is it valid to initialize x using memset(&x[0][0], 0, sizeof(x))?

int *p = &x[0][0];
memset(p, 0, sizeof(x))?

edit: I wonder whether the answers are different in C++ as well..! :)

2 Answers

The loop is not valid, see the comments by @EricPostpischil .

Yes, the memset approach is valid too. But it is not preferred solution. It operates on individual bytes so it can only ever be reasonably used for zeroing the memory.

C++

  • Value initialization T array[10][10] = {}; zeroes the array of primitives types, calls default constructors for classes.
  • std::fill(p,p+100,value) for assigning a specific value. There is not standard way how to initialize an array to non-zero values without listing them.
  • std::array<T,N> is the preferred way for arrays of known size.

C

cppreference

There is no special construct in C corresponding to value initialization in C++; however, = {0} (or (T){0} in compound literals) (since C99) can be used instead, as the C standard does not allow empty structs, empty unions, or arrays of zero length.

So, in case of nested arrays, use T array[10][10] = {{0}};.

You asked in title:

Can I use memset to initialize a 2 dimensional array?

Yes, as memset(...) only cares about byte count, you could use it like:

int x[10][10];
memset(&x, 0, sizeof(x));

But in C++, an empty initializer-list would do same, like:

int x[10][10] = {};

And in C since C99 (as mentioned in comments), we clould do instead:

int x[10][10] = {{0}};

Anyway, you say:

int q = x[0][10]; // This is an out-of-bounds access

Then asked is following valid:

int *p = &x[0][0];
for (int i = 0; i < 100; ++i)
   p[i] = 0;

Well yes, but only because you do something as simple as setting to zero, a more complex logic could require you to loop 2 dimensionally, like:

for (int x = 0; x < 10; ++x) {
    for (int y = 0; y < 10; ++y) {
        myArray[x][y] = something_more_complex_here;
    }
}
Related