0

This is my code:

char * name[]={"Dileep","Avina"};
name[0][1]='A';

here name[0] is an char* pointing to string literal "Dileep". So what will be the name[0][1]? Why it is giving me runtime error?

dlpsankhla
  • 132
  • 1
  • 2
  • 9
  • 6
    string-literals are constant, you can't change them. – tkausl Jun 09 '16 at 16:47
  • 1
    Possible duplicate of [Why do I get a segmentation fault when writing to a string initialized with "char \*s" but not "char s\[\]"?](http://stackoverflow.com/questions/164194/why-do-i-get-a-segmentation-fault-when-writing-to-a-string-initialized-with-cha) – Sean Cline Jun 09 '16 at 16:49
  • Stop using `const char*` or `char*` when writing C++, use `std::string`. – Hatted Rooster Jun 09 '16 at 16:49

2 Answers2

3

"Dileep" and "Avina" are string constants. Trying to change them is undefined behavior. If the OS puts them in read-only memory, you will get a fault.

Mark Tolonen
  • 166,664
  • 26
  • 169
  • 251
0

name[0] is an char* pointing to string literal "Dileep".

No, char * name[] is spurious. "Dileep" is string literal with type const char[7], and your code is not allowed since C++11 because of the conversion from string literal to char *. char * name[]={"Dileep","Avina"}; should be const char * name[]={"Dileep","Avina"};.

So what will be the name[0][1]?

It should be a const char.

Why it is giving me runtime error?

Modifying string literal is UB.

songyuanyao
  • 169,198
  • 16
  • 310
  • 405