memset用法小结

来源:互联网 发布:51软件测试业余班 编辑:程序博客网 时间:2024/05/19 23:11

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

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

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

一般常用的复制方式有:

[cpp] view plain copy
  1. int a[MAXN];  
  2. memset(a, 0, sizeof(a));//数组中的所有元素全为0  
  3. memset(a, -1, sizeof(a));//数组中的所有元素全为-1  
  4. 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
  1. //@auther Yang Zongjun  
  2. #include <iostream>  
  3. #include <cstdio>  
  4. #include <algorithm>  
  5. #include <cmath>  
  6. #include <cstring>  
  7. #include <string>  
  8.   
  9. using namespace std;  
  10. #define PI acos(-1.0)  
  11. #define EPS 1e-8  
  12. const int MAXN = 410000000;  
  13. const int INF = 2100000000;  
  14.   
  15. int a[MAXN];  
  16.   
  17. int main()  
  18. {  
  19.   
  20.     cout << a[0] << "  " << a[1] << endl;  
  21.     memset(a, -1, sizeof(a));  
  22.     cout << a[0]<< "  "  << a[1] << endl;  
  23.     memset(a, 0, sizeof(a));  
  24.     cout << a[0] << "  " << a[1] << endl;  
  25.     memset(a, 1, sizeof(a));  
  26.     cout << a[0] << "  " << a[1] << endl;  
  27.     memset(a, 2, sizeof(a));  
  28.     cout << a[0] << "  " << a[1] << endl;  
  29.     memset(a, 127, sizeof(a));  
  30.     cout << a[0] << "  " << a[1] << endl;  
  31.     return 0;  
  32. }  
运行结果:


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

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

0 0