strcpy strncpy (拷贝字符串)

    技术2025-09-19  139

     

    strcpy(拷贝字符串)

    表头文件 #include<string.h>

    定义函数 char *strcpy(char *dest,const char *src);

    函数说明 strcpy()会将参数src字符串拷贝至参数dest所指的地址。

    返回值    返回参数dest的字符串起始地址。

    附加说明 如果参数dest所指的内存空间不够大,可能会造成缓冲溢出(buffer Overflow)的错误情况,在编写程序时请特别留意,或者用  

                 strncpy()来取代。

     

     

    #include <stdio.h> #include <string.h> main() { char a[30] = "abcdefgh"; char b[] = "123456789"; printf("before strcpy() : %s/n",a); printf("after strcpy() : %s/n",strcpy(a,b)); } 运行结果:

     

    [root@localhost c]# gcc -o strcpy strcpy.c

    [root@localhost c]# ./strcpy

    before strcpy() : abcdefgh

    after strcpy() : 123456789

     

     

     

    strncpy(拷贝字符串)

    表头文件 #include<string.h>相关函数 bcopy,memccpy,memcpy,memmove

    定义函数 char * strncpy(char *dest,const char *src,size_t n);

    函数说明 strncpy()会将参数src字符串拷贝前n个字符至参数dest所指的地址。

    返回值    返回参数dest的字符串起始地址。

     

     

    #include <stdio.h> #include <string.h> main() { char a[30] = "abcdefgh"; char b[] = "123456789"; printf("before strncpy() : %s/n",a); printf("after strncpy() : %s/n",strncpy(a,b,6)); }

     运行结果:

    [root@localhost c]# gcc -o strncpy strncpy.c

    [root@localhost c]# ./strncpy

    before strncpy() : abcdefgh

    after strncpy() : 123456gh

    最新回复(0)