+ 1
About Pointers Again :(
I am trying to make a pointer that is affected by const. I mean the value that is pointed by pointer cannot change. char* const ptr="bla bla"; *ptr="hahaha"; And I am trying to change the value of bla bla with the help of pointer. But I am getting an error called "invalid conversion from 'const char*' to char. Can you help me?
5 Answers
+ 3
`const` means that you can't change the variable's contents! So you by definition can't. Your compiler will even try and optimize away `ptr` entirely if it can and there will be nothing for you to try and change.
Now, you *can* change a variable `x` from `const char*` to `char*`, like this:
const_cast<char*>(x)
But this is only safe if `x` used to be non-const, you made it const later, and now you want to un-const it again.
If you make your string non-const, then you can change it.
char* ptr = "bla bla";
(Or use std::string instead.)
+ 1
But when I looked to a programming book , I saw that when you use "const" before char, it means you cannot change the data of char. I mean the pointer itself can be reassigned. But we cannot modify the data pointed to by pointer. For example:
const char* ptr;
ptr="hahaha";
ptr="bla bla";//true
*ptr="hahaha";//false
And if we put const after char, it means you can change the data being pointed to. For example:
char* const ptr2="example";
ptr2="error";//false
*ptr2="normal";//it must be true. But I am getting errors. I think my process is true. But changing the value of "example" needs much more effort.
+ 1
Showing an example can be much more clear. By the way, thank you. @kurvius
+ 1
Up