Three ways to initialize arrays in C language: 1. Directly assign values when defining, with the syntax "data type arrayName[index] = {value};"; 2. Initialize using for loops, with the syntax "for (int i=0;i
The operating environment of this tutorial: windows7 system, c99 version, Dell G3 computer.
Three ways to initialize arrays in C language
1. Direct assignment during definition
int arr1[3] = {0};
Using {0} is the most concise way and is generally used when defining.
2. For loop initialization
int arr2[3]; for (int i = 0; i
The advantage of using a for loop is that each element can be set to a different value.
3. memset function
The memset function is declared as:
void *memset(void *str, int c, size_t n)
Replace n bytes (typedef unsigned int size_t) after the current position in str with c and return str.
int arr3[3];memset(arr3, 0, sizeof(int) * 3);
memset generally uses "0" to initialize the memory unit, usually to initialize the array or structure, or to clear the array or structure.
Generally, variables of types such as char, int, float, double, etc. can be initialized directly. If you use memset, it will be troublesome.
The sample codes of the three methods are as follows:
It should be noted that: the memset function initializes the memory block by bytes, so it cannot Use it to initialize an int array to a value other than 0 and -1.
memset is assigned a value of -1 or 0, and the final result is correct:
But use memset is assigned values other than -1 and 0, and the final result is not the expected value. For example, if the assignment is 1, it is as shown in the figure below:
#Because memset assigns a value to each byte, and it is known that an int is 4 bytes, then memset assigns a value When it is binary, it is:
00000001 00000001 00000001 00000001 = 16843009
[Related recommendations: C language video tutorial, Programming teaching 】
The above is the detailed content of How to initialize array in c language. For more information, please follow other related articles on the PHP Chinese website!