[英]How to initialise 2d array with all elements are 0?
I want to initialise a 2d array having all its elements are 0. I have tried this:我想初始化一个所有元素都是0的二维数组。我试过这个:
scanf("%d",&n);
int arr[n][n]={0};
but i got the [Error]:"variable-sized object may not be initialized"但我得到了 [错误]:“可变大小的对象可能未初始化”
So,how to do this?那么,该怎么做呢?
Be explicit.明确。
#include <string.h>
const int got = scanf("%d", &n);
int arr[n][n];
memset(arr, 0, sizeof arr);
Note that if got
isn't 1, the above has undefined behavior.请注意,如果
got
不是 1,则上面的行为未定义。 This is pretty dangerous.这是相当危险的。
Do in two steps:分两步做:
int a[n][n];
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
a[i][j] = 0;
}
}
probably the simplest method可能是最简单的方法
for(i = 0; i < n; i++)
{
for(j = 0; j < n; j++)
{
a[i][j] = 0;
}
}
use #include<string.h>
library well we have three methods to initialise it to 0使用
#include<string.h>
库,我们有三种方法将其初始化为 0
// the best and easy is using memset
int n;
scanf("%d",&n);
int array_d[n][n];
memset(array_d,0,sizeof(array_d));
// syntax memset(address_of_arr,anyvalue_u_want_Tointialise,sizeof_the_array_or_bytes); // 语法 memset(address_of_arr,anyvalue_u_want_Tointialise,sizeof_the_array_or_bytes); //hope u get it
//希望你能明白
case 2 // if it is global array then case 2 // 如果是全局数组则
int arr[1000][1000]={0};
case 3案例3
//using for loop
for(int =i;i<n;i++)
{
for(int j=0;j<n;j++)
{
arr[i][j]=0;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.