当前位置:网站首页>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 !
边栏推荐
- English learning plan
- To SystemC Beginners: the first program
- Leetcode 2176. Count equal and divisible pairs in an array
- Leetcode 2185. 统计包含给定前缀的字符串
- CSDN blog points rule
- Player actual combat 12 QT playing audio
- [MySQL advanced] index classification and index optimization scheme (V)
- Player practice 20 unpacking thread
- Comparator summary
- Llvm 13.1 new pass plug-in form [for win]
猜你喜欢
随机推荐
Is MySQL query limit 1000,10 as fast as limit 10? How to crack deep paging
Alibaba cloud development board haas510 submission device attributes
浅谈中国程序员为什么要跳槽?
My resume.
Create a small root heap and judge the node relationship (also.C\u str() substr(),atoi(),string. Use of find())
Axi4 increase burst / wrap burst/ fix burst and narrow transfer
Analysis of lua source code
测试工程师如何转型测开
What is automatic bidding? What are its advantages?
[advanced MySQL] evolution of MySQL index data structure (IV)
阿里云开发板HaaS510解析串口JSON数据并发送属性
How to realize the bidding strategy that pays more attention to transformation in the company's operation Google sem
Is Shell Scripting really a big technology?
Create a slice slice pit using the make method
Backtracking: Prime Rings
Codeforces Round #798 (Div. 2)(A~D)
Reverse analysis from x86 to x64tips
PostgreSQL14安装使用教程
如何使用android studio制作一个阿里云物联网APP
Leetcode 2176. 统计数组中相等且可以被整除的数对









