吾爱程序员:这里有好玩的游戏和软件
当前位置:首页C语言教程 → C/C++ 中的 strdup() 和 strndup() 函数

C/C++ 中的 strdup() 和 strndup() 函数

来源:网络 | 更新时间:2022-01-13 20:15:16
所述的strdup()strndup()函数用于复制的字符串。  strdup() :  语法 :  char *strdup(const char *s);   此函数返回一个指向以空字符结尾的字节字符串的指针,它是s 所指向的字符串的副本。获得的内存是使用malloc动态完成的,因此可以使用free()释放它。  它返回一个指向重复字符串s的指针。 下面是展示在 C 中使用 strdup() 函数的 C 实现:
// C program to demonstrate strdup()
#include<stdio.h>
#include<string.h>

int main()
{
char source[] = "52cxydh";

// A copy of source is created dynamically
// and pointer to copy is returned.
char* target = strdup(source);

printf("%s", target);
return 0;
}
输出:
52cxydh
strndup() :  语法
char *strndup(const char *s, size_t n);  
此函数类似于 strdup(),但最多复制n个字节。  注意:如果 s 比 n 长,则只复制 n 个字节,并在末尾添加一个 NULL ('')。 下面是展示在 C 中使用 strndup() 函数的 C 实现:
// C program to demonstrate strndup()
#include<stdio.h>
#include<string.h>

int main()
{
char source[] = "52cxydh";

// 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;
}
输出: 52cxy  

最新文章

热点资讯

手游排行榜

CopyRight 2020-2030吾爱程序员

鄂ICP备2021004581号-8

本站资源收集于网络,如有侵权请联系我们:35492删除0109@qq.com