c - 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
),不是吗?
解决方案
从您发布的报价中:
...它返回一个小于、等于或大于零的整数...
1
和都是108
大于 0 的整数。不能保证函数必须返回1
or -1
。
推荐阅读
- sql-server - SQL Server 用户定义函数同时使用 WITH、IF
- visual-studio-code - � 奇怪地存在于我的降价文件中
- verilog - 如何根据verilog中的参数将单个位扩展到多位?
- sql - SQL 查询仅获取基于状态的唯一值
- button - 创建一个从 2. 按钮弹出到 3. 网格的 1. 模式,该网格具有 4. 灯箱、5. 描述和 6. href 链接按钮
- javascript - Google Maps API Javascript - 从选择列表中创建标记
- paramiko - 通过 paramiko 使用一个 SSH 对象连续执行两个命令
- java - Json MongoDb Query中的Spring-boot可选ArrayList参数
- php - phpseclib 无法读取包含 guillemet 括号的 CSR 字段
- docker - 如何在 kubernetes 中添加 pod 依赖项,就像 docker-compose.yml 中的“depends_on”一样