Cライブラリ関数 -strncpy()

C 标准库 - <string.h>C標準ライブラリ - <string.h>

説明

Cライブラリ関数char *strncpy(char *dest, const char *src, size_t n)をsrcが指す文字列をdest、最大でもn文字コピーします。src の長さが n より小さい場合、dest の残りの部分はヌルバイトで埋められます。

宣言

以下は strncpy() 関数の宣言です。

char *strncpy(char *dest, const char *src, size_t n)

パラメータ

  • dest-- コピーされた内容を格納するためのコピー先配列を指します。
  • src-- コピーする文字列。
  • n-- ソースからコピーする文字数。

戻り値

この関数は、最終的にコピーされた文字列を返します。

例

以下の例は strncpy() 関数の使い方を示しています。ここでは、memset() 関数を使用してメモリ領域をクリアします。

例

#include <stdio.h> #include <string.h> int main() { char src[40]; char dest[12]; memset(dest, '\0', sizeof(dest)); strcpy(src, "This is example.com"); strncpy(dest, src, 10); printf("最終的なコピー先文字列: %s\n", dest); return(0); }

上記のプログラムをコンパイルして実行すると、次の結果が得られます。

最终的目标字符串: This is ru

C 标准库 - <string.h>C標準ライブラリ - <string.h>

その他の拡張