首页 > 解决方案 > n 太大的 strncmp 会给出奇怪的输出

问题描述

我有 2 个字符串要比较,我认为使用strncmp会比使用更好,strcmp因为我知道其中一个字符串的长度。

char * a = "hel";
char * b = "he"; // in my real code this is scanned so it user dependent
for(size_t i = 0; i < 5; i++){
    printf("strncmp: %d\n", strncmp(a,b,i));
}

我希望输出是

0
0
0
1   // which is the output of printf("strcmp: %d\n", strncmp(a,b));
1

因为仅在第 4 次迭代(i = 3)中,字符串开始有所不同,但我得到了

0
0
0
108  // guessing this is due to 'l' == 108 in ascii
108

我不明白为什么,正如男人所说:

strcmp()函数比较两个字符串 s1 和 s2。如果发现 s1 分别小于、匹配或大于 s2,则它返回一个小于、等于或大于零的整数。

strncmp()函数类似,只是它只比较 s1 和 s2 的前(最多)n 个字节。

这意味着它应该在到达 a 后停止'\0',因此只返回 1 (如strcmp),不是吗?

标签: cstrncmp

解决方案


从您发布的报价中:

...它返回一个小于、等于或大于零的整数...

1和都是108大于 0 的整数。不能保证函数必须返回1or -1


推荐阅读