文字列のコピー

文字列をコピーするには、strcpy関数を使います。

#include <stdio.h>
#include <string.h>

int main(){
    char str1[16] = "Hello ";
    char str2[16] = "World";

    strcpy(str1, str2);

    printf("%s\n", str1);
}

実行すると、以下のように表示されます。

World

strcpy関数は、str2の文字列をstr1にコピーします。str1の文字列はHelloからWorldに変わります。

以下にイメージ図を示します。str1str2は、それぞれ別のメモリ領域に配置されています。strcpy関数を使うことで、str2の文字列をstr1にコピーします。

文字列のコピー