C++ array initialization method: for loop or memset

1. Default initialization:

int arr[26] = {
    
    1}; // 初始化为{1,0,0,。。。,0}

Note: The initialization list only initializes the element at the indicated position, and other positions are initialized to 0 by default.
Reference: C/C++ array initialization

vector<int> ans(5); //vector默认初始化为0

2. For loop initialization:

int arr[26] = {
    
    1}; 
for(int i = 0; i<26;i++){
    
     // 全部初始化为-1
    arr[i] = -1;
} 

3. Initialization of memset:

int arr[26] = {
    
    -1}; 
memset(arr, -1, sizeof(arr));
char arr_1[10]; //单字符的变量可以正常初始化
memset(arr_1, 'c', sizeof(arr_1));

Note: First: memset functionInitialize the memory block by bytes, So it cannot be used to initialize the int array to a value other than 0 and -1 (unless the high byte and low byte of the value are the same).
Second: memset(void *s, int ch, size_t n); The actual range of ch should be 0~~255, because this functionOnly the last eight bits of ch can be assigned to each byte of the range you enter
memset Baidu Encyclopedia

to sum up:

1. It is convenient to initialize with memset, but note that values ​​other than 0 and -1 cannot be initialized.

Guess you like

Origin blog.csdn.net/qq_33726635/article/details/106114567