为什么strrchr()返回`char *`而不是`const char *`? [英] Why strrchr() returns `char*` instead of `const char*`?

查看:228
本文介绍了为什么strrchr()返回`char *`而不是`const char *`?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

函数 char* strrchr(const char *str, int ch) 返回一个指针()在最后出现的ch所在的str(const char *)中.

因此我们可以编写以下代码而无需任何强制转换:

So we can write the following code without any cast:

#include <string.h>
int main()
{
    const char CONSTSTR[] = "foo/bar/foobar.txt";
    char *ptr = strrchr (CONSTSTR, '/');
    *ptr++ = 'B';
    *ptr++ = 'A';
    *ptr++ = 'D';
}

返回char*而不是const char*有什么好处?

What is the advantage to return char* instead of const char* ?

编辑:
正如 Shafik Yaghmour 指出的那样, strchr实现如何工作?


As a Shafik Yaghmour pointed out, there are very good answers to How does strchr implementation work?

因为我的代码是C ++,所以我将使用<cstring>而不是<string.h>.谢谢您的回答;-)

As my code is in C++, I will use <cstring> instead of <string.h>. Thanks for your answers ;-)

但是,迈克·西摩的答案最适合这个问题.我什至添加了下面的更详细的答案,以明确地说strrchr()是C函数(不允许重载),该声明同时适合 const non-const 字符串.因为strrchr()可以用 non-const 字符串调用,所以返回的字符串也应该是 non-const .

However, the Mike Seymour's answer fits best the question. I have even added a more detailed answer below to clearly say as strrchr() is a C function (overload not permitted), the declaration fits both const and non-const strings. Because strrchr() can be called with a non-const string, the returned string should also be non-const.

推荐答案

在C语言中,函数必须像这样,或者在许多情况下强制用户使用躲猫猫强制转换:

In C, the function must either be like this, or force the user to use dodgy casts in many situations:

  • 如果使用非const指针,则无法搜索const字符串;
  • 如果它返回了const指针,则无法使用它来修改非const字符串.
  • If it took a non-const pointer, you couldn't search a const string;
  • If it returned a const pointer, you couldn't use it to modify a non-const string.

在C ++中,应包括<cstring>而不是已弃用的仅C标头.这将为您提供两个const正确的重载,这在C语言中是无法完成的:

In C++, you should include <cstring> rather than the deprecated C-only header. That will give you two const-correct overloads, which couldn't be done in C:

const char* strchr(const char* s, int c);
      char* strchr(      char* s, int c);

这篇关于为什么strrchr()返回`char *`而不是`const char *`?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆