0

I want to know why I have a compilation error when I try this :

char *name = "some_string";

And with this I don't have any problem :

const char*name = "some_string";

or

char name[] = "some_string";
Aduait Pokhriyal
  • 1,529
  • 14
  • 30
MathGuy1991
  • 57
  • 1
  • 6
  • Add some tags. For example, what language is this? Helps the right people find your question. – Mr Wednesday Apr 03 '14 at 04:01
  • That shouldn't produce an error, can you provide more context? – cwhelms Apr 03 '14 at 04:02
  • It seems you were doing some string operation like strcat,strncmp etc. – rakib_ Apr 03 '14 at 04:09
  • 1
    Possible duplicate [What is the difference between char s\[\] and char \*s in C?](http://stackoverflow.com/q/1704407) – Joseph Quinsey Apr 03 '14 at 04:16
  • All three are perfectly legal in C (though the first is potentially unsafe). If you get an error for the first, your probably compiling your code as C++. If you get an error message, you should include it in the question -- and you need to be aware of what language you're using. – Keith Thompson Apr 03 '14 at 04:44

1 Answers1

2

When you say

char *name = "some_string";

you are declaring a pointer to "some_string" and pointers are used to point already existing data and the existing data here is "some_string" which is placed under read only memory.

So const keyword is important.

const char*name = "some_string"; // this is proper way

and modifying the "some_string" after this declaration is illegal and causes undefined behavior...

When you say char name[] = "some_string";, "some_string" will be placed under read only memory and the same is copied to name[] array. later you can modify the content of name[].

For more info https://stackoverflow.com/a/18479996/1814023

Community
  • 1
  • 1