Line 4: invalid conversion from 'const char*' to 'char*' [-fpermissive]


  • 0
    O

    Why can't I use the c_str() function in line 4 to get the char* pointer of string and operate it?

    class Solution 
    {
    public:
    void reverseWords(string &s) {
        char *str=s.c_str(),*read;
        int num=1;
        
        for(char *strd=str;strd!=='\0';strd++)
        {
            str++;
            if(*strd=='\t')
            {
                while(*strd=='\t')
                strd++;
                num++;
            }
        }
        read=new char[num];
        num=1;
        read=str;
        
        for(char *strd=str;strd!=='\0';strd++)
        {
            str++;
            if(*strd=='\t')
            {
                while(*strd=='\t')
                strd++;
                read=read+num;
                read=strd;
                num++;
            }
        }
        read=read-num;
        for(;num!=-1;num--)
        {
            for(int i=0;*(read+num+i)!='\n'&&*(read+num+i)!='\t';i++)
            {
                printf("%c",*(read+num+i));
                i++;
            }
            printf('\t');
        }
      }
    };

  • 1
    S

    As the error message says, c_str() returns a "const char*". You cannot assign it to a non const char*. c_str() might expose part of the internal representation of the string, and thus it must return a const address to avoid any possible modification through this pointer.

    You should use a std::strcpy or something along this line to create a copy of the original string. However, this costs additional memory. So maybe directly operating on the original string is a better idea. This is C++ after all.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.