最佳答案
编辑: 我已经为这个例子添加了源代码。
我偶然发现了 这个例子:
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'
这让我想知道为什么会有人想要这种效果。看起来会很混乱。这个程序让我觉得你基本上可以复制别人的名字(例如。汤姆布洛考)与汤姆布洛763。
使用 strncpy()
结束了 strcpy()
的优点是什么?