曲径通幽论坛

标题: strdup() -- 复制字符串 [打印本页]

作者: beyes    时间: 2011-7-12 00:57
标题: strdup() -- 复制字符串
strcup() 的声明如下:
[C++] 纯文本查看 复制代码
#include <string.h>
char *strdup(const char *s);

该函数的作用是复制参数指针所指向字符串到函数所返回的字符串指针中,因为函数返回的指针所指向的空间是由 malloc() 分配的,所以可以用 free() 函数进行释放。

示例代码
[C++] 纯文本查看 复制代码

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

int main(void)
{
        const char *p = "hello world";
        char *sp;

        sp = strdup(p);

        printf ("%s\n", sp);

        free(sp);

        return 0;
}

运行输出
$ ./strdup
hello world





欢迎光临 曲径通幽论坛 (http://www.groad.net/bbs/) Powered by Discuz! X3.2