Почему эти две программы дают разные результаты в 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