n 太大的 strncmp 给出奇怪的输出
strncmp with too big of an n gives weird output
我有 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
我不明白为什么,正如 man 所说:
The strcmp()
function compares the two strings s1 and s2. It returns an integer less than, equal to, or greater than zero if s1 is found, respectively, to be less than, to match, or be greater than s2.
The strncmp()
function is similar, except it only compares the first (at most) n bytes of s1 and s2.
这意味着它应该在达到 '[=18=]'
后停止,因此只返回 1(如 strcmp
),不是吗?
来自您发布的引述:
... It returns an integer less than, equal to, or greater than zero ...
1
和 108
都是大于 0 的整数。不能保证函数必须 return 1
或 -1
.
我有 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
我不明白为什么,正如 man 所说:
The
strcmp()
function compares the two strings s1 and s2. It returns an integer less than, equal to, or greater than zero if s1 is found, respectively, to be less than, to match, or be greater than s2.The
strncmp()
function is similar, except it only compares the first (at most) n bytes of s1 and s2.
这意味着它应该在达到 '[=18=]'
后停止,因此只返回 1(如 strcmp
),不是吗?
来自您发布的引述:
... It returns an integer less than, equal to, or greater than zero ...
1
和 108
都是大于 0 的整数。不能保证函数必须 return 1
或 -1
.