0

first of all this is not duplicate one because same error Question asked before but in different context

1

code

#include<iostream>
#include<cstring>

int main()
{
    const char *s1;
    const char *s2="bonapart";
    
    s1=new char[strlen(s2)+1];
    strcpy(s1,s2);
    
    std::cout<<s1;
}

Output

[Error] invalid conversion from 'const char*' to 'char*' [-fpermissive]

Why such error ?

If I replace const char *s1 by char *s1 compile fine. But I think this const only saying that s1 is pointing to constant string means we can't modify that string whom it is pointing. It does not mean that s1 is constant ptr. please put some light on this.

Abhishek Mane
  • 619
  • 7
  • 20

2 Answers2

5

Why such error ?

Look at the declaration of strcpy:

char* strcpy( char* dest, const char* src );

Pay particular attention to the first parameter. And very particular attention to the type of the first parameter: char*. It isn't const char*.

Now, look at the type of the argument that you pass.

const char *s1;

It's not char*. It's const char*. You cannot pass a const char* into a function that accepts char* because former is not convertible to the latter, as the diagnostic message explains.

But I think this const only saying that s1 is pointing to constant string means we can't modify that string whom it is pointing.

That's exactly what const bchar* means. So, how do you expect strcpy to modify the content of the pointed string when you know that it cannot be modified? Technically in this case the pointed string isn't const, it's just pointed by a pointer-to-const

eerorika
  • 232,697
  • 12
  • 197
  • 326
  • `So, how do you expect strcpy to modify the content of the pointed string when you know that it cannot be modified?` ohh I get it so that's the reason why the first parameter of `strcpy` declaration is `char*` not `const char*` right ? and Thanks – Abhishek Mane May 20 '21 at 12:57
  • 1
    @AbhishekMane Well, yes. The function copies the string from the right argument to the left argument. – eerorika May 20 '21 at 13:02
  • can you help me. I Just started job after graduation and I have work on CPP REST SDK Library. I have to do that task in very short period of time. If you teach me for one hour it will great help. I will pay your charges. I don't know how to connect with you so commenting here. Please I really need your help – Abhishek Mane Jul 19 '22 at 17:16
2

As you say, const char *s1; means that the string pointed at by s1 is not modifyable.

On the other hand, strcpy(s1,s2); will modify the string pointed at by s1.

This is against the condition "the string pointed at by s1 is not modifyable".

MikeCAT
  • 73,922
  • 11
  • 45
  • 70