Fill multidimensional array elements with 0's

2020-02-09 11:31发布

I have a 2d and i want to set the elements to zero without looping all the elements

int a[100][200];

I can't initialize them at point of declaration.

标签: c++
12条回答
家丑人穷心不美
2楼-- · 2020-02-09 11:51

What exactly does "I can't initialize them at point of declaration" mean? "Don't know how to"? Or "can't modify the code there"?

The C++ language has a feature that initializes the entire array to 0 at the point of declaration

int a[100][100] = {};

(note, no explicit 0 is really necessary between the {}). Can you use it or not?

If you can't, then your options are: use the memset-hack, 1D-reinterpretation-hack or set each element explicitly by iterating through the array(s) (with or without the help fo std::fill).

查看更多
疯言疯语
3楼-- · 2020-02-09 11:57

Many answers used pointer arithmetic with fill. This can be done simpler:

int a[N][K];
fill(a[0], a[N], 0);

Basically, a[N] is a first memory address after the multi-dimensional array, no matter how many dimensions there are. This works too:

int a[N][K][L][M];
fill(**a[0], **a[N], 0);

The asterisks here dereferences the pointers down to int* type (the array brackets dereferences int**** to int***, the two asterisks does the rest of the job).

查看更多
做个烂人
4楼-- · 2020-02-09 12:01

For C++, you can use the std:fill method from the algorithm header.

int a[x][y];
std::fill(a[0], a[0] + x * y, 0);

So, in your case, you could use this:

int a[100][200];
std::fill(a[0], a[0] + 100 * 200, 0);

Of course, the 0 could be changed for any int value.

查看更多
贪生不怕死
5楼-- · 2020-02-09 12:02

Try memset(a,0,sizeof(a));

This simply overwrites the memory used by the array with 0 bytes. Don't do this for user-defined data types unless you really know what you do. There's also std::fill and std::fill_n, which is more C++ish (but not the easiest way here).

查看更多
唯我独甜
6楼-- · 2020-02-09 12:06

Try

int a[100][200] = {{0}};

If you initialize some (but not all) of the elements, the rest will be initialized to zero. Here, you are only explicitly initializing the first element of the first sub-array and the compiler is taking care of the rest.

查看更多
别忘想泡老子
7楼-- · 2020-02-09 12:08

C++ allows multidimensional arrays to be iterated entirely through by a base-element pointer. So you can use std::fill and pass it the very first nonarray element

std::fill(a[0] + 0, a[99] + 100, 0);

In C this is formally not allowed, and you would need to iterate through each sub-array separately, because iterating beyond the first subarray's past-the-end pointer causes undefined behavior in C. Nontheless, in practice this still works.

查看更多
登录 后发表回答