1. 程式人生 > >函式 —— memset()

函式 —— memset()

描述

C 庫函式 void *memset(void *str, int c, size_t n) 複製字元 c(一個無符號字元)到引數 str 所指向的字串的前 n 個字元。

引數

  • str -- 指向要填充的記憶體塊。
  • c -- 要被設定的值。該值以 int 形式傳遞,但是函式在填充記憶體塊時是使用該值的無符號字元形式。
  • n -- 要被設定為該值的位元組數。

例項1 —— 給陣列重新賦值

#include <string.h>
#include <stdio.h>
#include <memory.h>
int main(void)
{
	char buf[] = "Helloworle";
	char str[]="heihie!";	

	printf("before:=%s\n",buf);;
	memset(buf,0,strlen(buf));
	printf("after:=%s\n",buf);
	strcat(buf,str);
	printf("after strcat:= %s\n",buf);
	return 0;
}

讓我們編譯並執行上面的程式,這將產生以下結果:

before:=Helloworle
after:=
after strcat:= heihie!

例項2 —— 替換陣列中的部分值

#include <stdio.h>
#include <string.h>

int main ()
{
   char str[50];

   strcpy(str,"This is string.h library function");
   puts(str);

   memset(str,'$',7);
   puts(str);
   
   return(0);
}

讓我們編譯並執行上面的程式,這將產生以下結果:

This is string.h library function
$$$$$$$ string.h library function