所述的strdup()和strndup()函数用于复制的字符串。
strdup() :
语法 :
char *strdup(const char *s);
此函数返回一个指向以空字符结尾的字节字符串的指针,它是s 所指向的字符串的副本。获得的内存是使用malloc动态完成的,因此可以使用free()释放它。
它返回一个指向重复字符串s的指针。
下面是展示在 C 中使用 strdup() 函数的 C 实现:
输出:
输出:
52cxy
// 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;
}