I was going through some documentation which states that
First Case
char * p_var="Sack";
will create a constant string literal.
And hence code like
p_var[1]="u";
will fail because of that property.
Second Case
Also mentioned is that this is possible only for character literals and not for other data types through pointers. So code like
float *p="3.14";
will fail, resulting in a compiler error.
But when i try it out i don’t get compiler errors ,accessing it though gives me 0.000000f(using gcc on Ubuntu).
So regarding the above, i have three queries:
-
Why are string literals created in First Case read-only?
-
Why are only string literals allowed to be created and not other constants like float through pointers?
3. Why is Second Case not giving me compiler errors?
Update
Please discard the 3rd question and second case. I tested it by adding quotes.
Thanks
The premise is wrong: pointers don’t create any string literals, neither read-only nor writeable.
What does create a read-only string literal is the literal itself:
"foo"is a read-only string literal. And if you assign it to a pointer, then that pointer points to a read-only memory location.With that, let’s turn to your questions:
The real question is: why not? In most cases, you won’t want to change the value of a string literal later on so the default assumption makes sense. Furthermore, you can create writeable strings in C via other means.
Again, wrong assumption. You can create other constants:
Here, the
1.23fliteral is read-only. You can also assign it to a constant variable:Because the compiler cannot check in general whether your pointer points to read-only memory or to writeable memory. Consider this:
Here,
p[1] = 'x'is entirely legal – if we hadn’t re-assignedpbeforehand, it would have been illegal. Checking this cannot be generally done at compile-time.