曲径通幽论坛

标题: strcpy, strncpy -- 拷贝字符串函数 [打印本页]

作者: beyes    时间: 2009-4-28 03:37
标题: strcpy, strncpy -- 拷贝字符串函数
函数原型
#include <string.h>
char *strcpy(char *dest, const char *src);
char *strncpy(char *dest, const char *src, size_t n);
说明

strcpy() 函数把 src 指向的字符串拷贝到 dest 中,拷贝包含作后的 null 字节 ('\0')。

如下程序不会被报错
#include <stdio.h>
#include <string.h>
int main()
{
char *src = "hello world";
printf("%s\n", strcpy(src,src));

return 0;
}
也就是说,自己给自己拷贝不会报错,尽管字符串声明为 char *str ,而不是数组。
如果是下面的程序,则会出现段错误(编译无错)
#include <stdio.h>
#include <string.h>

int main()
{
    char *src = "hello world";
    char *dest = "yes";
    printf("%s\n", strcpy(src, dest));

    return 0;
}
说明
当用字符串文本来初始化类型为 char * 变量时,一些编译程序可能将字符串放置在内存中不能修改字符串的位置内。如果需要修改字符串文本,则应该存储在字符数组中,以确保可以在所有的系统上进行修改。自己给自己却可以复制成功这是因为跟底层函数的汇编代码实现有关。

strncpy()
函数里的参数 n 表示最多只从 src 那拷贝最多 n 字节。如果在 src 与第 n 个字节之间没有空字节的话,复制到 dest 里的字符串不会以 '\0' 结尾。如:
#include <stdio.h>
#include <string.h>

int main()
{
        char buf[20] = "hello world";
        char buf2[20];

        strncpy(buf2, buf, 5);
        printf("%s\n", buf2);

        return 0;
}
这样程序输出时会把第 n 个字节后的内容也都输出来:
beyes@linux-beyes:~/C/base> ./strncpy.exe
hello_xxxxx(乱码);
所以,得手动添加 '\0' 字符:
#include <stdio.h>
#include <string.h>

int main()
{
        char buf[20] = "hello world";
        char buf2[20];

        strncpy(buf2, buf, 5);
        buf2[5] = '\0';          /*添加 '\0' */
        printf("%s\n", buf2);

        return 0;
}





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