c++c++17overloadingc-stringsconst-pointer

Invalid conversion from ‘const char*’ to ‘char*’ with ```rindex``` function


I want to do something with string using the index and rindex function under c++17, but when I compile the program, this error poped up:

debug.cpp: In function ‘int main()’:
debug.cpp:7:27: error: invalid conversion from ‘const char*’ to ‘char*’ [-fpermissive]
    7 |  char* index_first = index(str,'c');
      |                      ~~~~~^~~~~~~~~
      |                           |
      |                           const char*
debug.cpp:9:27: error: invalid conversion from ‘const char*’ to ‘char*’ [-fpermissive]
    9 |  char* index_last = rindex(str,'c');
      |                     ~~~~~~^~~~~~~~~
      |                           |
      |                           const char*

Then I checked this program online, every function defines of index and rindex I saw are the same:

char* index(const char* s,int c);
char* rindex(const char* s,int c);

And heres my debug code:

#include <stdio.h>
#include <string.h>

int main()
{
    const char* str = "abcdefgabcdefg";
    char* index_first = index(str,'c');
    printf("the first index is %ld\n",index_first - str + 1);
    char* index_last = rindex(str,'c');
    printf("the last index is %ld\n",index_last - str + 1);
    return 0;
 }

I compile it using:

g++ -o debug debug.cpp -std=c++17

I want to know why can't I do that and the right way to use index and rindex functions and (or) the right function defines please.

Heres my environment:

Ubuntu LTS 20.04 (x64)
g++ (Ubuntu 9.4.0-1ubuntu1~20.04.1) 9.4.0

Thank you for all the help.


Solution

  • You are trying to assign returned pointers of the type const char * that are used within the functions to pointers of the type char *

    Actually the functions you are calling are declared like

    const char* index(const char* s,int c);
    const char* rindex(const char* s,int c);
    

    In C++ the functions can be overloaded like

    const char* index(const char* s,int c);
    const char* rindex(const char* s,int c);
    

    and

    char* index(char* s,int c);
    char* rindex(char* s,int c);
    

    the same way as some other standard C functions as for example the standard C function strchr.

    So you should write

    const char* index_first = index(str,'c');
    printf("the first index is %td\n",index_first - str + 1);
    const char* index_last = rindex(str,'c');
    printf("the last index is %td\n",index_last - str + 1);
    

    The result of subtracting two pointers has the signed integer type ptrdiff_t. So you need to use the conversion specifier %td instead of %ld.

    From the C Standard (7.21.6.1 The fprintf function)

    7 The length modifiers and their meanings are:

    t Specifies that a following d, i, o, u, x, or X conversion specifier applies to a ptrdiff_t or the corresponding unsigned integer type argument; or that a following n conversion specifier applies to a pointer to a ptrdiff_t argument.