C语言 百分网手机站

C语言的strcpy()和strncpy()函数

时间:2020-09-29 19:55:11 C语言 我要投稿

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 5
 
char * 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] != '')
 
i++;
 
if (st[i] == ' ')
 
st[i] = '';
 
else // must have words[i] == ''
 
while (get) != ' ')
 
continue;
 
}
 
return ret_val;
 
}

  该程序要求用户输入以q开头的单词,该程序把输入拷贝至一个临时数组中,如果第一个字母是q,程序调用strcpy()把整个字符串从临时数组拷贝至目标数组中。strcpy()函数相当于字符串赋值运算符。

  该程序的运行示例如下:

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
Enter 5 words beginning with q:
 
quackery [用户输入]
 
quasar [用户输入]
 
quilt [用户输入]
 
quotient [用户输入]
 
no more [用户输入]
 
no more doesn't begin with q!
 
quiz [用户输入]
 
Here are the words accepted:
 
quackery
 
quasar
 
quilt
 
quotient
 
quiz

  strcpy的其他属性:

  strcpy()的返回类型是char *,该函数返回的是第1个参数的值,即一个字符的'地址 第一个参数不必指向数组的开始,这个属性可用于拷贝数组的一部分。 strcpy()把源字符串中的空字符也拷贝在内。

  strncpy()函数

  strncpy()用来复制字符串的前n个字符,其原型为:

  char * strncpy(char *dest, const char *src, size_t n);

  【参数说明】dest 为目标字符串指针,src 为源字符串指针。

  strncpy()会将字符串src前n个字符拷贝到字符串dest。

  不像strcpy(),strncpy()不会向dest追加结束标记’’,这就引发了很多不合常理的问题。

  注意:src 和 dest 所指的内存区域不能重叠,且 dest 必须有足够的空间放置n个字符。

  【返回值】返回字符串dest。


【C语言的strcpy()和strncpy()函数】相关文章:

C语言指针函数和函数指针详解06-10

C语言中isalnum()函数和isalpha()函数的对比11-21

C语言函数 atoi()10-28

浅谈C语言函数10-22

C语言函数的含义10-04

C语言函数的参数和返回值10-05

C语言里面构造函数和析构函数的运用办法11-19

C语言函数的声明以及函数原型10-05

关于C语言对函数11-20