蓝桥杯基础知识3 memset()

蓝桥杯基础知识3 memset()

#include <bits/stdc++.h>
using namespace std;

int main(){
	int a[5];	//随机数
	for(int i = 0;i < 5; ++i)cout << a[i] << '\n';
	cout << '\n';
	
	memset(a, 0, sizeof a);	//0
	for(int i = 0;i < 5; ++i)cout << a[i] << '\n';
	cout << '\n';
	
	memset(a, -1, sizeof a);	//-1
	for(int i = 0;i < 5; ++i)cout << a[i] << '\n';
	cout << '\n';
	
	memset(a, 1, sizeof(a));	//16843009
	for(int i = 0;i < 5; ++i)cout << a[i] << '\n';
	cout << '\n';
	
	for(int i = 0;i < 5; ++i)cout << bitset<32>(a[i]) << '\n';
	cout << '\n';	//4*8位=32位:00000001000000010000000100000001
					//					1		1		1		1
	
	memset(a, 0x3f, sizeof(a));	//0x表示16进制,1061109567
	for(int i = 0;i < 5; ++i)cout << a[i] << '\n';
	cout << '\n';
	
	for(int i = 0;i < 5; ++i)cout << bitset<32>(a[i]) << '\n';
	cout << '\n';	//4*8位=32位:00111111001111110011111100111111
					//              3   f   3   f   3   f   3   f
	
	
	return 0;
}


C++ 在线工具 | 菜鸟工具 (runoob.com)

原码,反码,补码相互转换在线计算器 (23bei.com)

8位的系统中-1 补码为8个1,即11111111;0的补码是00000000

memset()是一个用于设置内存块值的函数。定义在<cstring>头文件中。函数声明:

void* memset(void*ptr, int value, size_t num);

//                      指针           值        重置大小

ptr:指向要设置值的内存块的指针。

value:要设置的值,通常是一个整数。

num:要设置的字节数。

memset()将ptr指向的内存块的前num个字节设置为value的值,返回一个指向ptr的指针。

memset() 的作用是在一段内存块中填充某个给定的值。

memset(arr, 0, sizeof(arr)) 或 memset(arr, 0, sizeof arr)将数组arr的所有元素设置为0.

对于非字符类型的数组可能产生未定义行为。memset会将每个byte设置成value。

char ~ 8bit ~ 1 Byte        int ~ 32bit ~ 4Byte

value = 1,二进制表示:00000001 00000001 00000001 00000001

//n必须为宏或者constexpr
int arr[n] = {0};    

​C/C++基础语法 定义一个数组并初始化为0 

//int arr[n];
arr[n] = {0};

把数组后面的一块大小为sizeof(int)的内存复制为0,这块内存不属于数组,具体执行结果与内存结构有关,属于典型未定义行为。

#include <bits/stdc++.h>
using namespace std;

int main(){
	int n = 5;
	
	int b[n] = {};
	for(int i = 0; i < 2*n; ++i)cout << b[i] << ' ';
	cout <<'\n';
	
	int a[n];
	a[n] = {0};
	for(int i = 0; i < 2*n; ++i)cout << a[i] << ' ';
	cout <<'\n';
	
	//0 0 0 0 0 32553 1101044968 32553 1101043616 32553 
	//-2129291136 32764 0 10 0 0 4198995 0 0 0 	
	
	int m = 4;
	
	int c[m] = {};
	for(int i = 0; i < 2*m; ++i)cout << c[i] << ' ';
	cout <<'\n';
	
	int d[m];
	d[m] = {0};
	for(int i = 0; i < 2*m; ++i)cout << d[i] << ' ';
	
	//0 0 0 0 -2129291136 32764 0 10 
	//0 0 4199454 0 0 0 0 0 

	return 0;
}

reference:

原码和补码之间的相互转化 - 知乎 (zhihu.com)

为什么0的补码形式只有一种?-CSDN博客​​​​​​

c++ - What's the difference between constexpr and const? - Stack Overflow

浅谈 C++ 中的 const 和 constexpr - 知乎

C 库函数 – memset() | 菜鸟教程 (runoob.com)

C++中memset(a, 0, sizeof(a))和a[n] = {0}有什么本质上的区别? - 知乎 (zhihu.com)

C++中memset()函数的用法详解_c++如果a数组是int类型,则memset是以每4个字节为一组赋值-CSDN博客

memset函数及其用法,C语言memset函数详解 (biancheng.net)

  • 18
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值