为什么要使用strncpy而不是strcpy?我偶然发现这个例子:char source[MAX] = "123456789";char source1[MAX] = "123456789";char destination[MAX] = "abcdefg";char destination1[MAX] = "abcdefg";char *return_string;int index = 5;/* This is how strcpy works */printf("destination is originally = '%s'\n", destination);return_string = strcpy(destination, source);printf("after strcpy, dest becomes '%s'\n\n", destination);/* This is how strncpy works */printf( "destination1 is originally = '%s'\n", destination1 );return_string = strncpy( destination1, source1, index );printf( "After strncpy, destination1 becomes '%s'\n", destination1 );产生了这一产出:destination is originally = 'abcdefg'
After strcpy, destination becomes '123456789'
destination1 is originally = 'abcdefg'
After strncpy, destination1 becomes '12345fg'这让我想知道为什么会有人想要这种效果。看起来会很混乱。这个程序让我觉得你基本上可以复制某人的名字。与汤姆·布罗科(Tom Brokaw)在一起。使用 strncpy() 过关 strcpy()?
3 回答
catspeake
TA贡献1111条经验 获得超0个赞
strncpy
strcpy
\0
n
n
n
strcpy
.
幕布斯7119047
TA贡献1794条经验 获得超8个赞
strncpy()
strncpy()
:
如果目标完全被填充,它不会在目的地放置一个NUL-Enminator;并且 它总是完全填充目的地,必要时使用null。
strcpy()
strncat()
if (dest_size > 0){ dest[0] = '\0'; strncat(dest, source, dest_size - 1);}
- 3 回答
- 0 关注
- 737 浏览
添加回答
举报
0/150
提交
取消