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
  • 583
  • 5
  • 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
  • 223,800
  • 12
  • 181
  • 301
  • `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
  • https://stackoverflow.com/q/67772282/11862989 can you answer this question please – Abhishek Mane Jun 02 '21 at 12:19
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
  • 69,090
  • 10
  • 44
  • 65