C/C++ の strdup() および strndup() 関数
の strdup() そして strndup() 関数は文字列を複製するために使用されます。
strdup() :
構文: char *strdup(const char *s);
この関数は、null で終わるバイト文字列へのポインタを返します。これは、 が指す文字列の複製です。 s 。取得されたメモリは malloc を使用して動的に行われるため、 free() を使用して解放できます。
複製された文字列へのポインタを返します s 。
以下は、C での strdup() 関数の使用法を示す C 実装です。
C
// C program to demonstrate strdup()> #include> #include> int> main()> {> > char> source[] => 'GeeksForGeeks'> ;> > // A copy of source is created dynamically> > // and pointer to copy is returned.> > char> * target = strdup(source);> > printf> (> '%s'> , target);> > return> 0;> }> |
出力:
GeeksForGeeks
strndup() :
構文: char *strndup(const char *s, size_t n);
この関数は strdup() に似ていますが、コピーできるのは最大でも n バイト。
注記 : s が n より長い場合、n バイトだけがコピーされ、最後に NULL (‘ ’) が追加されます。
以下は、C での strndup() 関数の使用法を示す C 実装です。
C
// C program to demonstrate strndup()> #include> #include> int> main()> {> > char> source[] => 'GeeksForGeeks'> ;> > // 5 bytes of source are copied to a new memory> > // allocated dynamically and pointer to copied> > // memory is returned.> > char> * target = strndup(source, 5);> > printf> (> '%s'> , target);> > return> 0;> }> |
出力:
Geeks
違いを表形式で見てみましょう -:
| strdup() | strndup() | |
| 1. | null で終わるバイト文字列へのポインタを返すために使用されます。 | null で終了するバイト文字列へのポインタを返すために使用されます。 |
| 2. | その構文は次のとおりです。 char * strdup( const char *str1 ); | その構文は次のとおりです。 char *strndup( const char *str, size_t size ); |
| 3. | で定義されています ヘッダーファイル | で定義されています ヘッダーファイル |
| 4. | 複製するヌル終了バイト文字列へのポインタであるパラメータを 1 つだけ取ります。 | 次の 2 つのパラメータを取ります。 2. str からコピーする最大バイト数 |
| 5. | 戻り値は、新しく割り当てられた文字列へのポインタです。 | エラーが発生した場合は null ポインタを返します。 |
参照: リナックスマン(7)