C++ memset
生活随笔
收集整理的這篇文章主要介紹了
C++ memset
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
memset的主要功能是對一片內(nèi)存進(jìn)行賦值(逐字節(jié)進(jìn)行)
包含在頭文件#include < cstring >中。
函數(shù)模板
void *memset(void *s, int v, size_t n);
s:數(shù)組名,或指向某一片內(nèi)存的指針名,
v:要填充的值,
n:填充的個數(shù),一般使用sizeof(s)。
實(shí)例
要注意memset是逐字節(jié)進(jìn)行賦值的,比如Int的話,占有4個字節(jié)(一個字節(jié)8位),每個字節(jié)都會被賦值為1,此時變?yōu)?br /> 00000001 00000001 00000001 00000001。因此使用memset給int類型的變量賦值的話,只能賦為0或-1。
#include <iostream>
#include <cstring>
using namespace std;
int main()
{int a;// 給a進(jìn)行賦值,每個字節(jié)的值都為0,即00000001。memset(&a,0,sizeof(a));cout<<a<<endl; // 輸出為0.int b;// 給b進(jìn)行賦值,由于memset是逐字節(jié)進(jìn)行賦值,int占有4個字節(jié)// 因此b的二進(jìn)制為00000001 00000001 00000001 00000001// 轉(zhuǎn)換為十進(jìn)制為16843009memset(&b,1,sizeof(b));cout<<b<<endl; //輸出16843009
}
#include <iostream>
#include <cstring>
using namespace std;
int main()
{int a[10];// 將a0~a9賦值為0。memset(a,0,sizeof(a));cout<<a[0]<<endl;
}
#include <iostream>
#include <cstring>
using namespace std;
int main()
{char str[] = "hellow world";memset(str,'*',4);// 輸出為 ****ow worldcout<<str<<endl;
}
總結(jié)
以上是生活随笔為你收集整理的C++ memset的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 阳煤平原出的八十斤一袋尿素多少钱一袋?
- 下一篇: 微信网名女生简单可爱