将可变大小的多维C数组初始化为零 [英] initialize a multidimensional C array of variable size to zero

查看:109
本文介绍了将可变大小的多维C数组初始化为零的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将尺寸可变的二维数组初始化为零.我知道可以对固定大小的数组完成此操作:

I want to initialize a two-dimensional array of variable size to zero. I know it can be done for a fixed-sized array:

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

但是如果我这样做是行不通的:

but it is not working if I do this:

int i = 10;
int j = 10;
int myarray[i][j] = {0};

是否有一种单行方式来执行此操作,还是必须遍历数组的每个成员?

Is there a one-line way of doing this or do I have to loop over each member of the array?

谢谢

推荐答案

您无法使用初始化程序对其进行初始化,但可以将数组 memset()设置为0.

You cannot initialize it with an initializer, but you can memset() the array to 0.

#include <string.h>

int main(void) {
  int a = 13, b = 42;
  int m[a][b];
  memset(m, 0, sizeof m);
  return 0;
}

注意:这是 C99 . C89 中声明m( int m [a] [b]; )是错误.

Note: this is C99. In C89 the declaration of m ( int m[a][b]; ) is an error.

这篇关于将可变大小的多维C数组初始化为零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆