C語言之memset函數

【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:

//#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


發佈了90 篇原創文章 · 獲贊 68 · 訪問量 66萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章