Difference between char *str="STRING" and char str[] = "STRING"?
Solution 1:
The two declarations are not the same.
char ptr[] = "string";
declares a char array of size 7
and initializes it with the characterss
,t
,r
,i
,n
,g
and \0
. You are allowed to modify the contents of this array.
char *ptr = "string";
declares ptr
as a char pointer and initializes it with address of string literal "string"
which is read-only. Modifying a string literal is an undefined behavior. What you saw(seg fault) is one manifestation of the undefined behavior.
Solution 2:
Strictly speaking a declaration of char *ptr
only guarantees you a pointer to the character type. It is not unusual for the string to form part of the code segment of the compiled application which would be set read-only by some operating systems. The problem lies in the fact that you are making an assumption about the nature of the pre-defined string (that it is writeable) when, in fact, you never explicitly created memory for that string yourself. It is possible that some implementations of compiler and operating system will allow you to do what you've attempted to do.
On the other hand the declaration of char test[]
, by definition, actually allocates readable-and-writeable memory for the entire array of characters on the stack in this case.