C语言之memset函数

xiaoxiao2021-02-28  24

【FROM MSDN && 百科】

原型:  void *memset(void *s,int ch,size_t n);

#include<string.h>

将 s 中前 n 个字节用 ch 替换并返回 s 。说明memset是按字节赋值的。

Sets the first num bytes of the block of memory pointed by ptr to the specified value (interpreted as an unsigned char).

将s所指向的某一块内存中的每个字节的内容全部设置为ch指定的ASCII值, 块的大小由第三个参数指定,这个函数

常为新申请的内存做初始化工作, 其返回值为指向S的指针。,它是对较大的结构体数组进行清零操作的一种最快方法

常见错误:

第一: 搞反了 ch 和 n 的位置. 一定要记住如果要把一个char a[20]清零,一定是 memset(a,0,20);

第二: 过度使用memset,

第三:函数参数传的是指针,而在函数中出现memset(a,0,sizeof(a));这里错误的原因是VC函数传参过程中的指针降级,导致sizeof(a),返回的是一个 something* 指针类型大小的的字节数,如果是32位,就是4字节。

例如有一个结构体Some x,可以这样清零:

memset(&x,0,sizeof(Some));

如果是一个结构体数组Some x[10],可以这样:

memset(x,0,sizeof(Some)*10);

-------------------------------------------------------------------

memset可以方便的清空一个结构类型的变量或数组。如:  struct sample_struct  {  char csName[16];  int iSeq;  int iType;  };对于变量 struct sample_strcut stTest;一般情况下,清空stTest的方法:  stTest.csName[0]={'\0'};  stTest.iSeq=0;  stTest.iType=0;用memset就非常方便:  memset(&stTest,0,sizeof(struct sample_struct));如果是数组:  struct sample_struct TEST[10];则  memset(TEST,0,sizeof(struct sample_struct)*10);另外:  如果结构体中有数组的话还是需要对数组单独进行初始化处理的。

 

DEMO:

[cpp]  view plain  copy //#define FIRST_DEMO  //#define SECOND_DEMO  #define THIRD_DEMO  #ifdef FIRST_DEMO  #include <stdio.h>  #include <conio.h>  #include <string.h>  int main(void)  {      char buffer[] = "This is a test of the memset function";      printf( "Before: %s\n", buffer );      memset(buffer,'*',4);      printf( "After: %s\n", buffer );      getch();      return 0;  }  #elif defined SECOND_DEMO  #include <stdio.h>  #include <conio.h>  #include <string.h>  int main(void)  {      int a[5];      int i;      /*     就是对a指向的内存的20个字节进行赋值,每个都用ASCⅡ为1的字符去填充,转为二进制后,1就是00000001,占一个字节。     一个INT元素是4 字节,合一起就是00000001000000010000000100000001,就等于16843009,就完成了对一个INT元素的赋值了     */      memset(a,1,20);  //用memset对非字符型数组赋初值是不可取的!      for (i=0;i<5;i++)      {          printf("%d\n",a[i]);      }      printf("\n");      getch();      return 0;  }  #elif defined THIRD_DEMO  #include <stdio.h>  #include <conio.h>  #include <string.h>  int main(void)  {      char ss[]="Golden Global View";      char *ss="Golden Global View";//出现内存访问冲突应该是因为ss被当做常量放入程序存储空间,      memset(ss,'G',6);      printf("%s\n",ss);      getch();      return 0;  }    #endif  
转载请注明原文地址: https://www.6miu.com/read-1700283.html

最新回复(0)