当前位置: C语言 -- 标准库 -- <string.h> -- strdup

strdup函数


概要:
#include <string.h>
char *strdup(const char *s);

描述:

该函数会在如同调用malloc函数分配的空间中,创建参数s指向字符串的副本。


参数:
const char *s

指向源字符串的指针。


返回值:

函数返回指向结果字符串首字符的指针。该返回指针可传递给free函数。如果无法分配内存,函数返回空指针。


范例:
1 
2 
3 
4 
5 
6 
7 
8 
9 
10 
11 
12 
13 
14 
15 
16 
17 
18 
19 
20 
21 
22 
23 
/*函数strdup范例*/

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

int main(void)
{
    const char *original = "Rome was not built in a day.";
    char *copy = strdup(original);
    
    if(copy == NULL)
    {
        puts("Copy creation failed.");
        return EXIT_FAILURE;
    }
    
    puts(copy);
    free(copy);
    
    return 0;
}


输出:

Rome was not built in a day.


相关内容:
memcpy 复制内存区域字符序列的函数。
memccpy 复制n个字符或者复制完首个指定字符的函数。
memmove 移动内存区域字符序列的函数。
strcpy 复制字符串的函数。
strncpy 从字符串中复制限定数量字符的函数。
strndup 创建字符数量限定的字符串的函数。


主要参考资料:

1、ISO/IEC 9899:2024