strncmp与n太大会产生奇怪的输出

CIs*_*ies 2 c strncmp

我有两个字符串要比较,我认为使用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));
}
Run Code Online (Sandbox Code Playgroud)

我期待输出

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

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

0
0
0
108  // guessing this is due to 'l' == 108 in ascii
108
Run Code Online (Sandbox Code Playgroud)

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

strcmp()函数比较两个字符串s1和s2.如果找到s1,则它返回小于,等于或大于零的整数,小于,匹配或大于s2.

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

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

Rei*_*ica 7

从您发布的报价中:

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

这两个1108是整数大于0的有没有保障功能必须返回1-1.

  • @CIsForCookies有什么奇怪的呢?这些函数做了不同的事情,并且因为这些低级例程很可能是超级优化的,所以它们可以*非常不同地实现. (3认同)