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 12:08

I tested this solution and it worked.

int arr[100][200];

for (int i=0; i<100; i++)
    for (int j=0; j<200; j++) (arr[i][j] = 0);

for (int i=0; i<100; i++)
    for (int j=0; j<200; j++) cout << (arr[i][j]);
查看更多
Explosion°爆炸
3楼-- · 2020-02-09 12:12

If this array is declared at file scope, or at function scope but with 'static', then it is automatically initialized to zero for you, you don't have to do anything. This is only good for one initialization, at program startup; if you need to reset it you have to code that yourself. I would use memset for that.

If it's declared at function scope without static, you need to use memset, or an explicit initializer - a single = { 0 } is enough, you don't need to write out all 2002 zeroes like someone else suggested.

查看更多
4楼-- · 2020-02-09 12:14

memset(a, 0, 100 * 200 * sizeof(int)); ought to do it.

查看更多
姐就是有狂的资本
5楼-- · 2020-02-09 12:15

The memset approach mentioned (memset(a,0,sizeof(a));) will work, but what about doing it the C++ way (per your tag), and using vector?

std::vector<std::vector<int> > a;
a.assign(100, std::vector<int>(200));
查看更多
SAY GOODBYE
6楼-- · 2020-02-09 12:15

Since the size is well-defined, all you need is the trailing parenthesis...

int a[100][200]();
查看更多
狗以群分
7楼-- · 2020-02-09 12:18

Use

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

This will initialize all the elements of the array with 0

查看更多
登录 后发表回答