当前位置:网站首页>Introduction of several ways to initialize two-dimensional arrays in C language (private way to initialize large arrays)
Introduction of several ways to initialize two-dimensional arrays in C language (private way to initialize large arrays)
2022-08-11 05:45:00 【FussyCat】
CSeveral ways of initializing two-dimensional arrays in the language are introduced
1、直接赋值
Suitable for arrays with fewer elements,The value of each element can be different.
int arr1[2][3] = {
{
5, 2, 4}, {
10, 2, 1} };
int arr1[2][3] = {
0}; /* 所有元素都初始化为0 */
int arr1[2][3] = {
1}; /* 只有arr1[0][0]为1,All other elements are initialized to 0 */
2、The loop assigns values to each element
Assign a value to each element of the array,The value of each element can be different.就是效率比较低.
int arr2[2][3];
int i, j;
for (i = 0; i < 2; i++) {
for (j = 0; j < 3; j++) {
arr2[i][j] = 2; /* In this example, both are assigned the same value for simplicity */
}
}
3、借用memset/memset_s初始化为0或-1
注意:memset/memset_sVariables can only be initialized as 0或-1
,Other values do not hold. 参考百度百科 The first of the common mistakes.
A lot of people don't notice this,容易犯错.
int arr3[10][10];
memset(arr3, 0, sizeof(arr3); /* 正常,arr3中的每个元素都为0 */
memset(arr3, -1, sizeof(arr3); /* 正常,arr3中的每个元素都为-1 */
memset(arr3, 2, sizeof(arr3); /* 异常,arr3Each element in is an outlier33686018 */
4、All elements of the array are initialized to the same value(It is convenient for initialization of large arrays)
as long as the values are the same,Especially when there are many array elements,推荐用此方法:
{ [0 … LENA-1][0 … LENB-1] = num };
This initialization method is relatively rare,But especially convenient,所以共享给大家.
#define ARR_LEN 100
int arr4[ARR_LEN][ARR_LEN] = {
[0 ... (ARR_LEN-1)][0 ... (ARR_LEN-1)] = 10 }; /* 100*100个元素都初始化为10 */
边栏推荐
猜你喜欢
随机推荐
ClionIDE通过指定编译器编译
信息学奥赛
Visual Studio上一些Error的解决方案
【网站小白】Hibernate插入数据成功,不报错,但是数据库中没有值
吃瓜教程task01 第2章 模型评估与选择
第5章 循环和关系表达式
QtDataVisualization 数据3D可视化
Pytorch最全安装教程(一步到位)
Who am I ?
task06 PyTorch生态
LeetCode43.字符串相乘 (大数相乘可用此方法)
vftpd本地可以连接,远程连接超时的解决
【转载】如何理解数据集中【训练集】、【验证集】和【测试集】
课堂练习--0708
(一)性能实时监控平台搭建(Grafana+Influxdb+Jmeter)
(二)性能实时监控平台搭建(Grafana+Prometheus+Jmeter)
一、Jmeter环境部署
【win10+cuda7.5+cudnn6.0安装caffe⑥】报错及处理方式
更新啦~人生重开模拟器自制
gradle-wrapper.jar说明