-1
#include<bits/stdc++.h>
    #include<iostream>
    using namespace std;
    #define nline "\n"
    
    int main(){
       //const char *p="hello world";
      // court<<p;

        char *p="hello world";
        cout<<p;
    
    
    }

C:\Users\Dell\AppData\Roaming\Sublime Text\Packages\User\cses2.cpp: In function 'int main()': C:\Users\Dell\AppData\Roaming\Sublime Text\Packages\User\cses2.cpp:7:10: warning: ISO C++ forbids converting a string constant to 'char' [-Wwrite-strings]* char *p="hello world"; ^~~~~~~~~~~~~

Kumawat Lalit
  • 410
  • 4
  • 8
  • 1
    String literals are made up of `const char`s. They may be stored in non-writeable memory. If you wan't something that you can modify: `char str[] = "hello world";` - the `char[]` is then initialized with the string literal. – Ted Lyngmo Aug 19 '22 at 10:56
  • Why should a pointer to a constant literal be non const? – πάντα ῥεῖ Aug 19 '22 at 10:56
  • In c++ it's rarely necessary to use `char`, use `std::string` instead or just use C. – user438383 Aug 19 '22 at 10:57
  • 1
    Side notes: (1) About `#include`: https://stackoverflow.com/questions/31816095/why-should-i-not-include-bits-stdc-h, (2) About `using namespace std;`: https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice. – wohlstad Aug 19 '22 at 10:59
  • Questions should include text (you know, a question) in addition to code and error messages. – JaMiT Aug 19 '22 at 14:26

1 Answers1

1

"hello world" is a const char[12]. A c-array of 12 constant (!) characters (note that one is for the null terminator).

In early C++ standards it was allowed to get a char * to a string literal due to compatibility with C. Though, it was nevertheless forbidden to actually modify the characters of the string literal via the char *.

This changed in C++11 and since then string literals have proper const correctness.

If you do want a string that can be modified, then use a std::string. Note that the pointer you obtain from the literal is not a string, its just a pointer to a (non-modifiable) c-string. If you want a string rather than a pointer to one, you need to use a string.

463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185