• 深入学习 memset 函数


      最近,和同学讨论了一下memset函数,趁着周五空闲做一总结。

      memset函数最常用的功能就是初始化数组了(主要是置零),如

    #include <iostream>
    #include <cstring>
    using namespace std;
    
    int main(int argc, char const *argv[])
    {
    	int A[10];
    	memset(A, 0, sizeof(A));
    	cout << A[0] << '	' << A[1] << endl;
    	return 0;
    }
    

        输出

    0    0
    

       但是,可以尝试一下,如果不是置零,比如置为1,得到的就不是预期的结果了,这是为何??

      要深入理解一个函数就要查看其原型。memset的原型是

    void *memset(void *dest, int c, size_t count);
    

        MSDN中,该函数作用描述为:Setd buffers to a specified character,即将缓存设定为一个专门的字符。对照函数原型,就是将已开辟的内存空间dest的手count个字节设定为的值设为。

      代码

    #include <iostream>
    #include <cstring>
    using namespace std;
    
    int main(int argc, char const *argv[])
    {
    	int A[10] = {0};
    	cout << A[0] << '	' << A[1] << endl;
    	memset(A, 1, 4);
    	cout << A[0] << '	' << A[1] << endl;
    	return 0;
    }
    

      运行结果 

    0       0
    16843009        0
    

      用计算器转换可以发现,确实是将每个字节设置为1

     

      果然还是“纸上得来终觉浅”!!

  • 相关阅读:
    UVA 11987 几乎就是并查集= =
    UVALive 5908 更新一下线段相交模板
    【poor几何】UVALive 5908 更新一下线段相交模板
    【poor几何】UVALive 5908 更新一下线段相交模板
    UVALive 3634 熟悉一下STL
    UVALive 3634 熟悉一下STL
    UVALive 3634 熟悉一下STL
    hdu2665 主席树模板题
    hdu2665 主席树模板题
    迷宫问题 POJ
  • 原文地址:https://www.cnblogs.com/zhaoyu1995/p/5396553.html
Copyright © 2020-2023  润新知