名稱空間
變體
操作

strndup

來自 cppreference.com
< c‎ | experimental‎ | dynamic
定義於標頭檔案 <string.h>
char *strndup( const char *str, size_t size );
(動態記憶體 TR)

返回一個指向空終止位元組字串的指標,該字串包含從 str 指向的字串中複製的最多 size 個位元組。如果前 size 個位元組中未遇到空終止符,則將其新增到複製的字串中。

返回的指標必須傳遞給 free 以避免記憶體洩漏。

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

與動態記憶體技術報告中的所有函式一樣,僅當實現定義了 __STDC_ALLOC_LIB__ 並且使用者在包含 string.h 之前將 __STDC_WANT_LIB_EXT2__ 定義為整數常量 1 時,才保證 strndup 可用。

目錄

[編輯] 引數

str - 指向要複製的以空字元結尾的位元組字串的指標
size - 要從 str 複製的最大位元組數

[編輯] 返回值

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

[編輯] 注意

此函式與 POSIX strndup 相同,不同之處在於它允許(但不要求)在錯誤時設定 errno

[編輯] 示例

#ifdef __STDC_ALLOC_LIB__
#define __STDC_WANT_LIB_EXT2__ 1
#else
#define _POSIX_C_SOURCE 200809L
#endif
 
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
 
int main(void)
{
    const char *s1 = "String";
    char *s2 = strndup(s1, 2);
    printf("strndup(\"String\", 2) == %s\n", s2);
    free(s2);
}

輸出

strndup("String", 2) == St

[編輯] 另請參閱

(動態記憶體 TR)
分配字串的副本
(函式) [編輯]
從一個字串複製一定數量的字元到另一個字串
(函式) [編輯]
分配記憶體
(函式) [編輯]