0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【C】初めてのC言語(13. メモリを扱う標準関数)

Posted at

はじめに

※今回の内容は、スッキリわかるC言語入門 第2版のp.378~p.383となります。

学習環境

  • 今回はpaiza.ioのC言語のエディタを使いました。

memcpy関数

void* memcpy(void* addr1, const void* addr2, size_t len)

// addr1:コピー先の先頭アドレス
// addr2:コピー元の先頭アドレス
// len:コピーするバイト数
  • メモリ領域をコピーするための関数です。
    • 第2引数のconst void*型は、「指している先の情報を変更できないvoid*型」だそうです。
    • 第3引数のsize_t型は、「長さ、大きさ、サイズを表現する型」となります。
  • 以下のコードでは、配列aの中身を配列bに丸ごとコピーしています。
  • memcpy関数によるコピーは、shallow copy(浅いコピー)と呼ばれます。
    • 「配列や構造体はコピーされるものの、それらが内部に持つポインタが指している先の領域までは複製されずに同じものを指す」という特徴があります。
Main.c
#include <stdio.h>

int main(void){
    int a[3] = {2, 4, 6};
    int b[3];

    memcpy(b, a, sizeof(a));   
    printf("bの要素を出力...\n");
    
    int length = sizeof(a) / sizeof(int);
    for(int i=0; i<length; i++) {
        printf("%d番目の要素は%dです。\n", i+1, b[i]);
    }
}
実行結果
bの要素を出力...
1番目の要素は2です。
2番目の要素は4です。
3番目の要素は6です。

memcmp関数

int memcmp(const void* addr1, const void* addr2, size_t len)

// addr1:比較先の先頭アドレス
// addr2:比較元の先頭アドレス
// len:比較するバイト数
// 戻り値:2つのメモリ領域が同じ内容ならば0を返す。
  • メモリ領域を比較するための関数です。
    • 第1引数および第2引数のconst void*型は、「指している先の情報を変更できないvoid*型」だそうです。
    • 第3引数のsize_t型は、「長さ、大きさ、サイズを表現する型」となります。
  • 以下のコードでは、配列aの中身と配列bの中身を全て比較しています。
    • sizeof(a)の代わりに4を代入すれば、先頭から4バイト目まで、つまり配列の最初の要素だけを比較できます。
Main.c
#include <stdio.h>

int main(void){
    int a[3] = {2, 4, 6};
    int b[3] = {2, 4, 6};
    
    int result = memcmp(a, b, sizeof(a));
    
    if (result==0) {
        printf("配列の中身は等しいです。\n");
    } else {
        printf("配列の中身は等しくないです。\n");
    }
}
実行結果
配列の中身は等しいです。

memset関数

void* memset(void* addr, int val, size_t len)

// addr:書き込み先の先頭アドレス
// val:書き込む値(0~255)
// len:書き込むバイト数
// 戻り値:addrと同じデータ(=書き込み先の先頭アドレス)
  • メモリ領域を初期化するための関数です。
    • 第3引数のsize_t型は、「長さ、大きさ、サイズを表現する型」となります。
  • 以下のコードでは、配列aの中身を「配列の先頭から4バイト目までを初期化」しています。
    • 4の代わりにsizeof(a)を代入すれば、配列の最初から最後の要素までを初期化できます。
Main.c
#include <stdio.h>
#include <string.h>

int main(void){
    int a[3];    
    memset(a, 1, 4);
    
    int length = sizeof(a) / sizeof(int);
    for(int i=0; i<length; i++) {
        printf("%d番目の要素は%dです。\n", i+1, a[i]);
    }
}
実行結果
1番目の要素は16843009です。
2番目の要素は-125704384です。
3番目の要素は-125704384です。

参考資料

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?