欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

C/C++中memset,memcpy的使用及fill對(duì)數(shù)組的操作

 更新時(shí)間:2020年12月08日 16:39:21   作者:lady_killer9  
這篇文章主要介紹了C/C++中memset,memcpy的使用及fill對(duì)數(shù)組的操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧

對(duì)數(shù)組的整體賦值,以及兩個(gè)數(shù)組間的復(fù)制容易出錯(cuò),這里使用string頭文件中的memset和memcpy進(jìn)行

不必遍歷數(shù)組,速度快。

之前沒有頭文件,顯示decla

頭文件:

代碼:

/*
 Project: 數(shù)組的整體賦值與復(fù)制 
 Date: 2018/07/31
 Author: Frank Yu
 memset(數(shù)組名,0或-1,字節(jié))
 memcpy(數(shù)組名,數(shù)組名,字節(jié))
*/
#include<iostream>
#include<cstring> //memset需要頭文件 
#include<cstdio>
#define n 5
using namespace std;
int main()
{
 int a[n];
 int b[n];
 memset(a,0,sizeof(a));//初始化為0
 //memset(b,1,sizeof(b));//初始化為1,錯(cuò)誤 
 memset(b,-1,sizeof(b)); 
 printf("請(qǐng)輸入%d個(gè)數(shù):\n",n);
 for(int i=0;i<n;i++)
 {
 scanf("%d",&a[i]);
 } 
 printf("第一個(gè)數(shù)組為:\n");
 for(int i=0;i<n;i++)
 {
 printf("%d ",a[i]);
 } 
 printf("\n");
 printf("第二個(gè)數(shù)組為:\n");
 for(int i=0;i<n;i++)
 {
 printf("%d ",b[i]);
 } 
 printf("\n");
 memcpy(a,b,sizeof(b));//b的元素復(fù)制給a 
 printf("第一個(gè)數(shù)組被第二個(gè)數(shù)組覆蓋后:\n");
 for(int i=0;i<n;i++)
 {
 printf("%d ",a[i]);
 } 
 return 0;
}

結(jié)果截圖:

20190304更新...

fiil函數(shù)需要頭文件 algorithm fill執(zhí)行速度不如memset

fill(first,last,val)對(duì)數(shù)組進(jìn)行初始化,first,last為地址,val為值。例如,fill(a,a+5,123) 將數(shù)組a的前5個(gè)初始化為123。

補(bǔ)充知識(shí):C++ 中使用memset和memcpy 對(duì)字符串和字符串?dāng)?shù)組處理

我就廢話不多說了,大家還是直接看代碼吧~

#include <iostream>
#include <string.h>
using namespace std;
struct SomeInfo
{
 char id[30];
 char name[30];
};
 
struct TotalInfo
{
 char total[20];
 SomeInfo my[10];
};
 
class myClass
{
 public:
 myClass()
 {
 }
 
 ~myClass()
 {
 } 
 
 void memcopy(int ,TotalInfo);
 void print();
 private:
 TotalInfo m_totalInfo;
 int m_count;
}; 
 
void myClass::memcopy(int count ,TotalInfo info)
{
 m_count = count;
 memcpy(&m_totalInfo,&info,sizeof(m_totalInfo));
}
void myClass::print()
{
 std::cout << m_totalInfo.total << std::endl;
 for (int i = 0; i != m_count ; ++i)
 {
 std::cout << m_totalInfo.my[i].id << std::endl;
 std::cout << m_totalInfo.my[i].name << std::endl;
 }
}
int main()
{
 myClass here = myClass();
 TotalInfo totalInfo;
 memset(&totalInfo, 0, sizeof(totalInfo));
 char total[20] = "totalInfo.total"; 
 memcpy(totalInfo.total,total,20); 
 int count = 5;
 for (int i = 0; i != count ; ++i)
 {
 char _id[30] = "totalInfo.Some.id";
 char _name[30] = "totalInfo.Some.name";
 memcpy(totalInfo.my[i].id, _id,sizeof(_id));
 memcpy(totalInfo.my[i].name, _name,sizeof(_name));
 }
 here.memcopy(count, totalInfo);
 here.print();
 return 0;
}

在main函數(shù)的第三行,memset初始化新申請(qǐng)的內(nèi)存。memset:作用是在一段內(nèi)存塊中填充某個(gè)給定的值,它是對(duì)較大的結(jié)構(gòu)體或數(shù)組進(jìn)行清零操作的一種最快方法。

一共三個(gè)參數(shù),地址,請(qǐng)零(目前做的是清零動(dòng)作,而不是char型值),地址空間大小。

memcpy 也有三個(gè)參數(shù),一個(gè)目標(biāo)地址,源地址,和 大小。

以上這篇C/C++中memset,memcpy的使用及fill對(duì)數(shù)組的操作就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論