-3

I am running the below code. I am getting run time error.

#include <iostream>
using namespace std;

int main() {
    char *p="hello";
    //p="Hi";
    *p='G';
    cout<<*p;
    return 0;
}

if this is giving error then what is use of const char *p="hello";In this case my string should be constant not in char *p="hello"

Csq
  • 5,775
  • 6
  • 26
  • 39
Aman
  • 9
  • 7
  • You can't change the memory where a `char [5] ` literal is placed by the linker. Also switch all warnings on when compiling. – πάντα ῥεῖ Sep 30 '14 at 16:33
  • 3
    This code is no longer legal since C++11. String literals now decay to `const char*` only. – jrok Sep 30 '14 at 16:36
  • 1
    possible duplicate of [What are all the common undefined behaviours that a C++ programmer should know about?](http://stackoverflow.com/questions/367633/what-are-all-the-common-undefined-behaviours-that-a-c-programmer-should-know-a) – Deduplicator Sep 30 '14 at 16:36
  • 2
    Use `char p[] = "hello";` if you want to create an array of 6 _non-constant_ chars, initialized with the values `{ 'h', 'e', 'l', 'l', 'o', '\0' }` – Jonathan Wakely Sep 30 '14 at 16:43

1 Answers1

1
char *p="hello";
*p='G';

You make p point to a constant, "hello". But then you try to modify what p points to. By definition, constants cannot be modified.

David Schwartz
  • 179,497
  • 17
  • 214
  • 278