[C言語]strcpyを使わないで文字列をコピー!基本的な複写方法についても

C言語
広告

C言語において、文字列をコピーする方法にはいくつかのアプローチがあります。

この記事では、strcpy 関数を使用せずに文字列をコピーする方法と、同じ処理を strcpy 関数を使って行う方法について解説します。

どちらの方法も理解することで、文字列処理の基本的な考え方を深めることができます。

SPONSORLYNC

strcpyを使わないで文字列をコピーする

C言語において、文字列をコピーする一般的な手法は、

文字列を構成する各文字を順番に新しい領域にコピーしていくことです。

以下に、この手法を実現する簡単なコード例を示します。

#include <stdio.h>

void copyString(char dest[], const char src[]) {
    int i = 0;
    while (src[i] != '
#include <stdio.h>

void copyString(char dest[], const char src[]) {
    int i = 0;
    while (src[i] != '\0') {
        dest[i] = src[i];
        i++;
    }
    dest[i] = '\0';  // 文字列の終端を設定
}

int main() {
    char source[] = "Hello, C!";
    char destination[20];

    // 文字列のコピー
    copyString(destination, source);

    // 結果の表示
    printf("Source: %s\n", source);
    printf("Destination: %s\n", destination);

    return 0;
}
') { dest[i] = src[i]; i++; } dest[i] = '
#include <stdio.h>

void copyString(char dest[], const char src[]) {
    int i = 0;
    while (src[i] != '\0') {
        dest[i] = src[i];
        i++;
    }
    dest[i] = '\0';  // 文字列の終端を設定
}

int main() {
    char source[] = "Hello, C!";
    char destination[20];

    // 文字列のコピー
    copyString(destination, source);

    // 結果の表示
    printf("Source: %s\n", source);
    printf("Destination: %s\n", destination);

    return 0;
}
'; // 文字列の終端を設定 } int main() { char source[] = "Hello, C!"; char destination[20]; // 文字列のコピー copyString(destination, source); // 結果の表示 printf("Source: %s\n", source); printf("Destination: %s\n", destination); return 0; }

この例では、copyString 関数を用いて文字列をコピーしています。

while ループを使用して、終端文字 (‘\0’) に達するまで各文字をコピーし、

最後に終端文字を追加しています。

広告

strcpyを利用して文字列を複写する

C言語の標準ライブラリには、文字列をコピーするための strcpy 関数が用意されています。

以下は、この関数を使用した文字列コピーの例です。

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

int main() {
    char source[] = "Hello, C!";
    char destination[20];

    // strcpy関数を使用した文字列のコピー
    strcpy(destination, source);

    // 結果の表示
    printf("Source: %s\n", source);
    printf("Destination: %s\n", destination);

    return 0;
}

strcpy 関数を使うと、簡潔に文字列をコピーできますが、注意が必要です。

元の文字列 (source) のサイズがコピー先のバッファ (destination) のサイズよりも大きい場合、

バッファオーバーフローが発生し、不正な動作やセキュリティ上の脆弱性が生じる可能性があります。

そのため、十分なメモリが確保されていることを確認することが重要です。

広告

まとめ

文字列のコピーには様々な方法がありますが基本的な考え方は元の文字列から

一つずつ文字を取り出し新しい領域に配置していくことです。

strcpy 関数を使う場合は、メモリサイズに注意して使用するようにしましょう。

これらの基本的な手法を理解することで、文字列操作においてより柔軟に対応できるようになります。

C言語
広告
塩竈Code
タイトルとURLをコピーしました