strchr 的问题
我不明白为什么下面的 C 代码不起作用:
int obtainStringLength(char* str, char c1, char c2) {
char* firstOcurrence = strchr(str, c1);
char* endOcurrence = strchr(str, c2);
return 2+(endOcurrence - firstOcurrence) / sizeof(char*);
}
这个想法是找出 c1
和 c2
之间有多少个字符:
printf("%d\n", obtainStringLength("abc def ghi", 'a', 'i')); //should yield 11
不幸的是,这总是打印 1. 问题是什么? strchr
不应该像 C# 的 string.IndexOf()
一样工作吗?
I can't get why the following bit of C code doesn't work:
int obtainStringLength(char* str, char c1, char c2) {
char* firstOcurrence = strchr(str, c1);
char* endOcurrence = strchr(str, c2);
return 2+(endOcurrence - firstOcurrence) / sizeof(char*);
}
The idea is to find how many characters are between c1
and c2
:
printf("%d\n", obtainStringLength("abc def ghi", 'a', 'i')); //should yield 11
Unfortunately, this is always printing 1. What is the problem? Shouldn't strchr
work like C#'s string.IndexOf()
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
除以
sizeof(char*)
?这是不正确的 - 两个指针相减的结果是与值的数量相对应的数值 (ptrdiff_t
),而不是指针或地址差。计算长度时还存在相差一的错误。所以最后一行应该是这样的:
Division by
sizeof(char*)
? That's incorrect - the result of subtracting two pointers is a numerical value (ptrdiff_t
) corresponding to the number of values, not a pointer or difference of addresses.There's also the off-by-one error in calculating the length. So that last line should look like:
由于不理解指针算术,您的 return 语句有几个问题。
指针减法已经除以元素大小,而且
char*
无论如何都是错误的类型。并且您应该添加 1,而不是 2。
Your return statement has several problems, due to not understanding pointer arithmetic.
Pointer subtraction already divides by the element size, and
char*
was the wrong type anyway.And you should be adding 1, not 2.
因为每个字符正好占用sizeof(char)
个字节;不是sizeof (char*)
字节。而
sizeof (char)
根据定义为 1,因此您可以省略它:Because each character occupies exactlysizeof (char)
bytes; notsizeof (char*)
bytes.And
sizeof (char)
is, by definition 1, so you can omit it:不,strchr() 返回正在查找的字符的指针(地址),如果未找到该字符,则返回 NULL。
这与 IndexOf() 有很大不同。
No, strchr() returns a pointer (the address of) the character being sought, or NULL if the character was not found.
That's very different from IndexOf().