当前位置:网站首页>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 */

边栏推荐
- Flask框架学习:路由的尾部斜杠
- c 指针学习(1)
- (1) Docker installs Redis in practice (one master, two slaves, three sentinels)
- Redis - the solution to the failure of connecting to the redis server in linux using jedis
- 怎么用管理员方式打开压缩包
- QtDataVisualization 数据3D可视化
- 如何设置pip安装的国内源
- arraylist之与linkedlist
- QT Mat转HObject和HObject转Mat 图像视觉处理
- pytorch和tensorflow函数对应表
猜你喜欢
随机推荐
深入理解线程、进程、多线程、线程池
如何设置pip安装的国内源
C语言——文件操作详解(1)
RK3399上的Tengine实践笔记
(一)性能实时监控平台搭建(Grafana+Influxdb+Jmeter)
【转载】CMake 语法 - 详解 CMakeLists.txt
curl 命令调用接口demo
【备忘】于仕琪的libfacedetection相关
[转载]Verilog testbench总结
Win下安装不同版本的MinGW(g++/gcc)以及对应clion编辑器的配置
程序员小白的自我救赎之路。
QT Mat转HObject和HObject转Mat 图像视觉处理
C语言自定义类型——枚举类型讲解
做款好喝的茶饮~
gradle-wrapper.jar说明
C语言自定义数据类型——联合体
注解式编程小记
性能效率测试
pytorch中tensor 生成的函数
一、Jmeter环境部署








