Reputation: 1396
char s[] = "abc";
char t[3] = "abc";
are effectively identical to:
char s[] = { 'a', 'b', 'c', '\0' };
char t[] = { 'a', 'b', 'c' };
And the following:
char *word = "abc";
word[0] = 'd';
places word
in read-only memory, causing the illegal memory operation word[0] = 'd'
to error.
Is this only the case with char
s? I can't get an error when I do something like this:
int array[] = {1, 2, 3};
int *p = array;
p[0] = 0; // No error here
array[1] = 1; // or here
Upvotes: 3
Views: 382
Reputation: 320361
There's no exact analog for string literals for other array types. But you can come somewhat close by using a const-qualified compound literal
const int *p = (const int []) { 1, 2, 3 };
There is a chance it will be placed into read-only memory, and might crash the program if an attempt is made to modify it (after casting away constness that is). Another similarity with string literals is that const-qualified compound literals might share storage.
One obvious difference between compound literals and string literals is that string literals always have static storage duration, while block-level compound literals have automatic storage duration.
Upvotes: 1
Reputation: 263167
It applies only to string literals.
A string literal implicitly creates an array object of type char[N]
containing the character in the literal followed by a terminating \0'
character. This object has static storage duration and is read-only. (It's not const
, for historical reasons, but attempting to modify it has undefined behavior.)
When you write:
char *ptr = "abc";
you're creating ptr
as a pointer object, and initializing it to point to the read-only static array containing "abc"
. (You can prevent attempts to modify it by defining it as const
.)
When you write:
char arr[] = "abc";
you're creating arr
as an array object, of type char[4]
, and copying the contents of the static read-only array into that object. arr
is not read-only.
int array[] = {1, 2, 3};
creates an array object and initializes it as shown. There are no "integer array literals" that act like string literals. (There almost are -- see "compound literals" -- but those don't have the same read-only semantics as string literals.)
Note that this:
char t[3] = "abc";
is a special case: if an array is initialized with a string literal, and there isn't room for the terminating '\0'
, then only the non-null characters are copied to the array. As a result, t
does not contain a string, just an unterminated sequence of characters. This isn't particularly relevant to your question.
Upvotes: 7