-4

What is the difference between these two definitions?

char *string = "MyString";
char string[] = "MyString";

As much as I know, the first one is a pointer to a string.

ForceBru
  • 43,482
  • 10
  • 63
  • 98
Hairi
  • 3,318
  • 2
  • 29
  • 68
  • C does not have a string type. And the answer can be found by learning the language basics. – too honest for this site Apr 28 '16 at 13:48
  • Their type and the number of indirections a compiler creates to access the object. – Jens Apr 28 '16 at 13:49
  • see also http://stackoverflow.com/questions/30533439/string-literals-vs-array-of-char-when-initializing-a-pointer – Eugene Sh. Apr 28 '16 at 13:51
  • [What is the difference between char s`[]` and char *s in C?](http://stackoverflow.com/questions/1704407/what-is-the-difference-between-char-s-and-char-s-in-c?rq=1) – Lundin Apr 28 '16 at 13:55

1 Answers1

1

The first is a pointer to a string literal, the second is an array initialized with the contents of the string literal (which BTW when optimized points exactly to where string points).

The first one lives in the read only segment of the program's memory and thus cannot be modified.

The second one is an array of 9 elements and you can modify any of the 9 elements including the termnating null byte that is not explicitly set in the code in your question.

Iharob Al Asimi
  • 52,653
  • 6
  • 59
  • 97