当前位置:网站首页>Three common methods of C language array initialization ({0}, memset, for loop assignment) and their principles
Three common methods of C language array initialization ({0}, memset, for loop assignment) and their principles
2022-06-12 14:14:00 【zou_ albert】
C In language , There are three ways to initialize arrays :
1、 When making a statement , Use {0} initialization ;
2、 Use memset;
3、 use for Loop assignment .
that , What are the principles and efficiency of these three methods ? See the test code below :
#define ARRAY_SIZE_MAX (1*1024*1024)
void function1()
{
char array[ARRAY_SIZE_MAX] = {
0}; // Use... When declaring {0} Initialize to full 0
}
void function2()
{
char array[ARRAY_SIZE_MAX];
memset(array, 0, ARRAY_SIZE_MAX); // Use memset Method
}
void function3()
{
int i = 0;
char array[ARRAY_SIZE_MAX];
for (i = 0; i < ARRAY_SIZE_MAX; i++) //for Loop assignment
{
array[i] = 0;
}
}
efficiency :
Perform the above three methods respectively , If you count the average time, you can get : for The cycle wastes the most time ,{0} And memset It takes almost .
principle :
1、for Loop assignment , It's circular assignment , No explanation.
2、memset, Easy to find memset Internal implementation code , There's no explanation here
3、{0} How is it realized internally ?
Compile the above code into assembly format as follows :
function1 as follows :
pushl %ebp
movl %esp, %ebp
subl $1048600, %esp
leal -1048584(%ebp), %eax
movl $1048576, %edx
movl %edx, 8(%esp)
movl $0, 4(%esp)
movl %eax, (%esp)
call memset
leave
ret
function2 as follows :
pushl %ebp
movl %esp, %ebp
subl $1048600, %esp
movl $1048576, 8(%esp)
movl $0, 4(%esp)
leal -1048584(%ebp), %eax
movl %eax, (%esp)
call memset
leave
ret
It can be seen from the assembly code that ,{0} Initialization mode , Called memset function !
The selection of three methods :
1、for It's a waste of time , Don't suggest ( Actually memset The interior is also realized by circulation , It's just memset After strict optimization , So the performance is higher );
2、{0} There may be portability issues , Although most compilers see {0} All initializes the array to 0, But it's not guaranteed that all compilers are implemented like this ;
3、 comprehensive 1、2, Recommended memset Method .
Add :
Look at the following example :
…
wchar_t wname[128]={0};
char cname[256]={0};
…
I'm interested in :
1. The result of this assignment .
2. Whether this form conforms to the standard coding rules ?
We have the following information :
The number of initialization values can be less than the number of array elements . When the number of initialization values is less than the number of array elements , The previous initializes the corresponding values in order , The following initialization is 0( Global or static arrays ) Or uncertain value ( Local arrays ).
I believe the information above is C and C++ The standard of language , But in actual compiler processing , It might be different from the norm . Because compilers follow language specifications in principle , But for local arrays, what are the uncertain values , How to deal with , The compiler can handle it flexibly . I tested three compilers , In fact, the value given by the compiler is fixed , All are 0.
/*
Always thought that int a[256]={0}; It's a a All elements of are initialized to 0,int a[256]={1}; It's a a All elements are initialized to 1. It's not the same thing to check the memory while debugging , Turn it over 《The C++ Programming Language》 Finally, there is a conclusion .PDF I don't think so , I translated this chapter , as follows
5.2.1 Array initialization
Arrays can be initialized with a column value , for example
int v1[] ={1,2,3,4};
char v2[]={‘a’,‘b’,‘c’,0};
When an array is defined, no size is specified , When initializing with a list , Then the size of the array is determined by the number of list elements during initialization . therefore v1 and v2 Respectively int[4] and char[4] type . If the array size is explicitly specified , When the number of specified elements exceeds this size during initialization, an error will occur . for example :
char v3[2] ={‘a’,‘b’,0}; // error : Too many initialization values
char v3[3] ={‘a’,‘b’,0}; // correct
If the number of elements specified at initialization is less than the size of the array , The rest of the elements are initialized to 0. for example
int v5[8]={1,2,3,4};
Equivalent to
int v5[8]={1,2,3,4,0,0,0,0};
Note that there is no array assignment in the form :
void f()
{
v4={‘c’,‘d’,0}; // error : It's not an array assignment
}
If you want to replicate like this , Please use vector(16 Chapter three ) perhaps valarray(22 Chapter four ).
Character arrays can be easily initialized directly with strings ( Refer to Chapter 5 2.2 Section )
Translation notes : Namely Here it is char alpha []=“abcdefghijklmn”;
*/
for instance :
#include <iostream.h>
int array1[5]={
1,2,3};
static int array2[5]={
1};
void main()
{
int arr1[5]={
2};
static int arr2[5]={
1,2};
int n;
cout <<"global: ";
for(n=0; n<5; n++)
cout <<" " <<array1[n];
cout <<" global static: ";
for(n=0; n<5; n++)
cout <<" " <<array2[n];
cout <<" local: ";
for(n=0; n<5; n++)
cout <<" " <<arr1[n];
cout <<" local static: ";
for(n=0; n<5; n++)
cout <<" " <<arr2[n];
cout <<endl;
}
In this case , Both global and static arrays are initialized to 0, However, the local array is not uncertain to the previous , The following is to use gcc,VC6.0,tuborC++ Separately compiled results ( Be careful gcc use g++ compile c++ file ,gcc It won't link libraries ):
/*
GCC It can also be used to compile C Procedure and C++ Program . Generally speaking ,C The compiler uses the suffix of the source file to determine if it is C The procedure is still C++ Program . stay Linux in ,C The suffix name of the source file is .c, and C++ The suffix name of the source file is .C or .cpp.
however ,gcc Commands can only compile C++ Source file , And not automatically and C++ The library connection used by the program . therefore , Usually use g++ Order to complete C++ Program compilation and linking , The program will automatically call gcc Implement compilation .
*/
This indicates the value of an element that is not initialized to a local array , These compilers set it to 0. however , If you don't initialize the array , That is, it is not initialized with a list when it is defined , Then the value of the local array depends on the compiler, which is unpredictable to the programmer . You can test the compilers when you have time , But in the vc Medium is 0xcc. So be very careful when initializing local arrays . But global arrays and static arrays will still be correctly assigned to 0 It's worth it .
Reiterate the importance of variable initialization !
边栏推荐
- Player actual combat 16 xdecode class
- Analysis of lua source code
- Visual studio common shortcuts
- Introduction to database system (Fifth Edition) notes Chapter 1 Introduction
- Llvm pass-- virtual function protection
- Cmake basic tutorial - 02 b-hello-cmake
- Alibaba cloud development board haas510 responds to UART serial port instructions
- Talk about the top 10 classic MySQL errors
- CSDN blog points rule
- 肝了一个月的原创小袁个人博客项目开源啦(博客基本功能都有,还包含后台管理)
猜你喜欢

Player actual combat 22 to solve the problems of flower screen and Caton

Alibaba cloud development board haas510 connects to the Internet of things platform -- Haas essay solicitation

Talk about the top 10 classic MySQL errors

chapter19 Allocation

After reading the question, you will point to offer 16 Integer power of numeric value

阿里云开发板HaaS510解析串口JSON数据并发送属性

正点原子STM32F429核心板的插座型号

Leetcode 2176. 统计数组中相等且可以被整除的数对

Getting started alicloud haas510 open board DTU (version 2.0) --510-as

Player practice 15 xdemux and avcodecparameters
随机推荐
Redis core configuration and advanced data types
[video lesson] a full set of tutorials on the design and production of Android studio Internet of things app -- all mastered during the National Day
Player actual combat 22 to solve the problems of flower screen and Caton
如果要打造品牌知名度,可以选择什么出价策略?
Tool notes - common custom tool classes (regular, random, etc.)
Design of PLC intelligent slave station based on PROFIBUS DP protocol
Player practice 26 adding slider and window maximization
Alibaba Cloud Development Board haas510 submission Device Properties
公司运营中更注重转化的出价策略,如何实现? —Google sem
CUDA error: CUBLAS_ STATUS_ NOT_ INITIALIZED when calling `cublasCreate(handle)`
Implementation of Ackermann function with simulated recursion
Is Shell Scripting really a big technology?
Shell notes
Implementation and debug of process hiding under x64
PostgreSQL14安装使用教程
Display logs in the database through loganalyzer
动态搜索广告智能查找匹配关键字
阿里云开发板HaaS510连接物联网平台--HaaS征文
Player actual combat 21 audio and video synchronization
Shell脚本到底是什么高大上的技术吗?