+ 1

Confusion on const char*

Hi We can have const int* and int* const.. I am aware about these two along with int const * as well as const int * const. I have just captured these into sample code below: Question is related to const char* It is neither as per const int* or int* const Am I missing something or const char* is totally different? What is constant in this declaration? https://code.sololearn.com/c9ig21YSVy5e/?ref=app

8th Apr 2022, 9:57 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
4 Respuestas
+ 3
Well ------ const int* p1 = &a; ++a;//works as a is not const p1 = &b;//works as pointer is not const ++p1;// works and p1 is not pointing to b now but points to some next memory location //++(*p1);//not work as const int means int value is const and p1 cant modify pointed value ------ ------ const char* p = "Hello\n"; p = "World\n"; //works as pointer is not const ++p; // works and *p* is not pointing to 'W' now but points to some next memory location ('o') cout << *p << "\n"; //++(*p); //not work as const char means char value is const and *p* cant modify pointed value ------ Question is why you think *p* is not behaving like *p1* ?
9th Apr 2022, 6:10 AM
Arsenic
Arsenic - avatar
+ 2
I'm not quite sure what you mean? const char* functions the same as const int*. In this case, 'char*' or 'char* const' works a little different than 'int*' or 'int* const' only because the pointed-to string is stored in read only memory, so you can't assign it a different character. If that is what you mean.
8th Apr 2022, 10:13 PM
Dennis
Dennis - avatar
+ 2
char* name = "blah blah"; <= this will compile as normal but if you try to modify it at run time, your prog will fail. const char* name = "blah blah" ; <= this will NOT even compile if your code tries to modify it.
8th Apr 2022, 11:46 PM
rodwynnejones
rodwynnejones - avatar
+ 1
Thanks rodwynnejones , Dennis and Arsenic I was confused about what is const in case of const char* Char* is nothing but string kind of and hence "hello" string is constant.. so can't modify the same like Hello or Dello In short this we should define as const char* as what we assigned initially is in code or constant section
9th Apr 2022, 7:41 AM
Ketan Lalcheta
Ketan Lalcheta - avatar