😸

[C] memcpy 関数

に公開

機能

バイト単位でメモリ内容をコピーする標準関数[1]

使用例

abcdef と表示する

\n は改行を表す エスケープシーケンス[2]

コード

char src[] = "abcdef";
char dst[10];
memcpy(dst, src, 7); // 終端の\0もコピーする
printf("%s\n", dst);
全文
#include <stdio.h>
#include <string.h>
void main() {
    char src[] = "abcdef";
    char dst[10];
    memcpy(dst, src, 7); // 終端の\0もコピーする
    printf("%s\n", dst);
}

実行結果

abcdef

Hello, World! を変数から表示する

コード

char message[20];
const char *str = "Hello, World!";
memcpy(message, str, strlen(str) + 1);
printf("%s\n", message);
全文
#include <stdio.h>
#include <string.h>
void main() {
    char message[20];
    const char *str = "Hello, World!";
    memcpy(message, str, strlen(str) + 1);
    printf("%s\n", message);
}

実行結果

Hello, World!
脚注
  1. 指定したバイト数だけ、ソースのアドレスからデスティネーションのアドレスへデータをコピーする関数。構造体や配列など任意のバイナリデータにも使える。 ↩︎

  2. 改行やタブなど、画面に表示されない制御文字のこと。 ↩︎

Discussion