编辑:我已经添加了示例的源代码。
我遇到了这个例子:
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 );
产生了这个输出:
目的地最初是='abcdefg' strcpy 后,destination 变为 '123456789' destination1 最初是 = 'abcdefg' strncpy 后,destination1 变为 '12345fg'
这让我想知道为什么有人会想要这种效果。看起来会很混乱。这个程序让我觉得你基本上可以用 Tom Bro763 复制某人的名字(例如 Tom Brokaw)。
使用 strncpy()
over strcpy()
有什么好处?