strchr 的问题

发布于 2024-10-07 01:33:24 字数 518 浏览 3 评论 0原文

我不明白为什么下面的 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*);
}

这个想法是找出 c1c2 之间有多少个字符:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

没有你我更好 2024-10-14 01:33:24

除以sizeof(char*)?这是不正确的 - 两个指针相减的结果是与值的数量相对应的数值 (ptrdiff_t),而不是指针或地址差。

计算长度时还存在相差一的错误。所以最后一行应该是这样的:

return 1 + (endOcurrence - firstOcurrence);

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 1 + (endOcurrence - firstOcurrence);
緦唸λ蓇 2024-10-14 01:33:24

由于不理解指针算术,您的 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.

涙—继续流 2024-10-14 01:33:24

因为每个字符正好占用sizeof(char)个字节;不是 sizeof (char*) 字节。

sizeof (char) 根据定义为 1,因此您可以省略它:

return 1 + (endOcurrence - firstOcurrence);

Because each character occupies exactly sizeof (char) bytes; not sizeof (char*) bytes.

And sizeof (char) is, by definition 1, so you can omit it:

return 1 + (endOcurrence - firstOcurrence);

月下客 2024-10-14 01:33:24

不,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().

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文