4

为什么这两个程序在 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
4

2 回答 2

3

strcmpstrncmp都保证结果将包括:

零值表示两个字符串相等。大于零的值表示第一个不匹配的字符在 str1 中的值大于在 str2 中的值;小于零的值表示相反。

返回的实际数字(1/-1 或 12/-13)是特定于实现的,可以是任何值。唯一重要的部分是两者都返回 0、小于零或大于零。在这方面,他们提供了相同的答案。

于 2011-12-08T05:45:25.020 回答
2

来自 strncmp:

返回一个整数值,表示字符串之间的关系:零值表示两个字符串中比较的字符都相等。大于零的值表示第一个不匹配的字符在 str1 中的值大于在 str2 中的值;小于零的值表示相反。

显然 strcmp 总是为不相等的字符返回 1 或 -1,而 strncmp 返回不相等的字符之间的差异。由于该行为未定义,因此不是问题。

于 2011-12-08T05:46:55.917 回答