memset用法小结

xiaoxiao2021-02-28  145

memset函数是按一个字节一个字节来给数组或者是结构体赋值的,

给字符数组复制时可以赋任意值,详见:百度百科memse函数点击打开链接

但需要注意的是给int型的数组复制时的几点注意:

一般常用的复制方式有:

[cpp] view plain copy int a[MAXN];   memset(a, 0, sizeof(a));//数组中的所有元素全为0   memset(a, -1, sizeof(a));//数组中的所有元素全为-1   memset(a, 127, sizeof(a));//数组中的所有元素全为2139062143(可以将其视为INF)   但切不可认为memset(a, 1, sizeof(a))后数组中的所有元素全为1了,这样数组的每个元素其值为:16843009(因为memset函数是按一个字节一个字节来赋值的),。每个都用ASCⅡ为1的字符去填充,转为二进制后,1就是00000001,占一个字节。一个INT元素是4字节,合一起是0000 0001,0000 0001,0000 0001,0000 0001,转化成十六进制就是0x01010101,就等于16843009

[cpp] view plain copy //@auther Yang Zongjun   #include <iostream>   #include <cstdio>   #include <algorithm>   #include <cmath>   #include <cstring>   #include <string>      using namespace std;   #define PI acos(-1.0)   #define EPS 1e-8   const int MAXN = 410000000;   const int INF = 2100000000;      int a[MAXN];      int main()   {          cout << a[0] << "  " << a[1] << endl;       memset(a, -1, sizeof(a));       cout << a[0]<< "  "  << a[1] << endl;       memset(a, 0, sizeof(a));       cout << a[0] << "  " << a[1] << endl;       memset(a, 1, sizeof(a));       cout << a[0] << "  " << a[1] << endl;       memset(a, 2, sizeof(a));       cout << a[0] << "  " << a[1] << endl;       memset(a, 127, sizeof(a));       cout << a[0] << "  " << a[1] << endl;       return 0;   }   运行结果:

还有就是数组长度大的数组尽量放在堆内存区(main函数外),这样可以获得较大长度的数组,若放在main函数内(存放于栈内存区)则数组长度稍大就会爆栈

原文->http://blog.csdn.net/yang_zongjun/article/details/39025581

转载请注明原文地址: https://www.6miu.com/read-58186.html

最新回复(0)