[C++]數組處理相關函數(memcpy/memset等)


頭文件:string.h或者memory.h

【1】void *memcpy(void *dest, const void *src, size_t n);//數組元素拷貝
  功能:從源src所指的內存地址的起始位置開始拷貝n個字節到目標dest所指的內存地址的起始位置中

【2】void *memset(void *s, int ch, size_t n);//重置數組元素與初始化
  功能:將s中當前位置后面的n個字節 (typedef unsigned int size_t )用 ch 替換並返回 s 。
  memset:作用是在一段內存塊中填充某個給定的值,它是對較大的結構體或數組進行清零操作的一種最快方法

#include<iostream>
#include<string.h>
using namespace std;

int main(){
    int array_a[12] = {23,45,6,7,4776,834,99954};
    int array_b[12];

    memset(array_b, -1, sizeof(array_a)); //將數組b的各元素初始化為-1

    memcpy(array_b, array_a+1, sizeof(int)*6);
    for(int i=0;i<12;i++){
        printf("%d ", array_b[i]);
    }
    return 0;
}

【3】int memcmp(const void *buf1, const void *buf2, unsigned int count);//數組元素比較

  功能:比較內存區域buf1和buf2的前count個字節。注意:按照字節比較的

  返回值:當buf1<buf2時,返回值小於0;當buf1==buf2時,返回值=0;當buf1>buf2時,返回值大於0

 

【4】void *memmove( void* dest, const void* src, size_t count );//

  功能:由src所指內存區域復制count個字節到dest所指內存區域。

  memmove用於從src拷貝count個字節到dest,如果目標區域和源區域有重疊的話,memmove能夠保證源串在被覆蓋之前將重疊區域的字節拷貝到目標區域

  但復制后src內容會被更改。但是當目標區域與源區域沒有重疊則和memcpy函數功能相同。

// memmove.c
#include <stdio.h>
#include <string.h>

int main(void){
    char s[]="Golden Global View";
    memmove(s,s+7,strlen(s)+1-7);
    printf("%s",s);
    getchar();
    return 0;
}

=>output:

  Global View

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM