Use memset to initialize the pit of int type array

Header file: #include<memory.h>

Or directly upload the universal header file: #include<bits/stdc++.h> (I found out that the header file can also be plug-in, so I won’t be afraid of it anymore, I’ll break it~)

But, don’t be happy too early,

When memset initializes an int type array, it only supports initializing all elements in the array to 0 or -1 ~

The test code:

#include<bits/stdc++.h>
using namespace std;
int main(){
	int e[10][10];
	//数组初始化全部元素为-1 
	cout<<"数组初始化全部元素为-1: "<<endl;
	memset(e,-1,sizeof(e));
	for(int i=0;i<10;i++){
		for(int j=0;j<10;j++)
			cout<<e[i][j]<<" ";
		cout<<endl; 
	}
	//数组初始化全部元素为 0 
	//或者最简单的方式,在定义数组时 ---> int e[10][10]={0};
	cout<<"数组初始化全部元素为0: "<<endl;
	memset(e,0,sizeof(e));
	for(int i=0;i<10;i++){
		for(int j=0;j<10;j++)
			cout<<e[i][j]<<" ";
		cout<<endl; 
	}
	return 0;	
} 

result:

What if memset(e,1,sizeof(e)); is executed ? (Don’t do such a stupid thing!!!)

Trial and error is me:

Well, the test part is over. We need to analyze why this happens. How can 0 and -1 be initialized, but 1 is not enough?

The memset in Baidu Encyclopedia:
void *memset(void *s, int ch, size_t n);
Set all the contents of the first n bytes in a block of memory pointed to by s to the ASCII value specified by ch, the size of the block Specified by the third parameter, this function usually initializes the newly applied memory, and its return value is a pointer to S.

memset relies on binary for initialization, int is 4 bytes, memset assigns a value to each byte, that is, for example,

因为计算机中用二进制补码表示数字,0和二进制补码为全0,-1的二进制补码为全1!

0,补码是00000000 00000000 00000000 00000000结果是0

-1,补码是11111111 11111111 11111111 11111111结果也是-1

So it is just a beautiful coincidence that 0 and -1 can be initialized ~

But memset() can initialize a bool array  memset(b, true or false, sizeof(b));//b is a bool array

Guess you like

Origin blog.csdn.net/WKX_5/article/details/114629671