为什么这两个程序在 VC++2008 中给出不同的输出?
毕竟,比较的是相同的字符串。
strcmp__usage.c
#include <stdio.h>
#include <string.h>
main()
{
char targetString[] = "klmnop";
printf ("Compare = %d\n", strcmp(targetString, "abcdef"));
printf ("Compare = %d\n", strcmp(targetString, "abcdefgh"));
printf ("Compare = %d\n", strcmp(targetString, "jlmnop"));
printf ("Compare = %d\n", strcmp(targetString, "klmnop"));
printf ("Compare = %d\n", strcmp(targetString, "klmnoq"));
printf ("Compare = %d\n", strcmp(targetString, "uvwxyz"));
printf ("Compare = %d\n", strcmp(targetString, "xyz"));
}
输出
Compare = 1
Compare = 1
Compare = 1
Compare = 0
Compare = -1
Compare = -1
Compare = -1
strncmp_usage.c
#include <stdio.h>
#include <string.h>
main()
{
char targetString[] = "klmnopqrstuvwxyz";
int n = 6;
printf ("Compare = %d\n", strncmp(targetString, "abcdef", n));
printf ("Compare = %d\n", strncmp(targetString, "abcdefgh", n));
printf ("Compare = %d\n", strncmp(targetString, "jlmnop", n));
printf ("Compare = %d\n", strncmp(targetString, "klmnop", n));
printf ("Compare = %d\n", strncmp(targetString, "klmnoq", n));
printf ("Compare = %d\n", strncmp(targetString, "uvwxyz", n));
printf ("Compare = %d\n", strncmp(targetString, "xyz", n));
}
输出
Compare = 10
Compare = 10
Compare = 1
Compare = 0
Compare = -1
Compare = -10
Compare = -13