名稱空間
變體
操作

strdup

來自 cppreference.com
< c‎ | string‎ | byte
定義於標頭檔案 <string.h>
char *strdup( const char *src );
(自 C23 起)

返回一個指向以空字元結尾的位元組字串的指標,該字串是 src 所指向的字串的副本。新字串的空間獲取方式如同呼叫了 malloc。返回的指標必須傳遞給 free 以避免記憶體洩漏。

如果發生錯誤,則返回空指標,並且可能設定 errno

目錄

[編輯] 引數

src - 指向要複製的以空字元結尾的位元組字串的指標

[編輯] 返回值

指向新分配字串的指標,如果發生錯誤則為 null 指標。

[編輯] 注意

該函式與 POSIX strdup 相同。

[編輯] 示例

#include <string.h>
#include <stdio.h>
#include <stdlib.h>
 
int main(void)
{
    const char *s1 = "Duplicate me!";
    char *s2 = strdup(s1);
    printf("s2 = \"%s\"\n", s2);
    free(s2);
}

輸出

s2 = "Duplicate me!"

[編輯] 參閱

分配一個指定大小的字串副本
(函式) [編輯]
將一個字串複製到另一個字串
(函式) [編輯]
分配記憶體
(函式) [編輯]
釋放先前分配的記憶體
(函式) [編輯]