- 相关推荐
C语言的strcpy()和strncpy()函数
对于C语言来说,什么是strcpy()和strncpy()函数呢?这对于想要学习C语言的小伙伴来说,是必须要搞懂的事情,下面是小编为大家搜集整理出来的有关于C语言的strcpy()和strncpy()函数,一起看看吧!
strcpy()函数
strcpy() 函数用来复制字符串,其原型为:
char *strcpy(char *dest, const char *src);
【参数】dest 为目标字符串指针,src 为源字符串指针。
注意:src 和 dest 所指的内存区域不能重叠,且 dest 必须有足够的空间放置 src 所包含的字符串(包含结束符NULL)。
【返回值】成功执行后返回目标数组指针 dest。
strcpy() 把src所指的由NULL结束的字符串复制到dest 所指的数组中,返回指向 dest 字符串的起始地址。
注意:如果参数 dest 所指的内存空间不够大,可能会造成缓冲溢出(buffer Overflow)的错误情况,在编写程序时请特别留意,或者用strncpy()来取代。
示例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 | /* copy1.c -- strcpy() demo */#include#include // declares strcpy()#define SIZE 40#define LIM 5char * s_gets(char * st, int n);int main(void){char qwords[LIM][SIZE];char temp[SIZE];int i = 0;printf("Enter %d words beginning with q:
", LIM);while (i < LIM && s_gets(temp, SIZE)){if (temp[0] != 'q')printf("%s doesn't begin with q!
", temp);else{strcpy(qwords[i], temp);i++;}}puts("Here are the words accepted:");for (i = 0; i < LIM; i++)puts(qwords[i]);return 0;}char * s_gets(char * st, int n){char * ret_val;int i = 0;ret_val = fgets(st, n, stdin);if (ret_val){while (st[i] != '
' && st[i] != ' |