Sona said:
Hi,
What's the advantage/disadvantage of using a "const char*" over a
"char*" ?
It's not a question of advantages/disadvantages. It's a
question of using what's appropriate.
I read some place that char* are string literals
Wherever you read that, stop reading there. That's
completely false. 'char*' expresses a type, 'pointer-to-char'.
It is not a 'string literal'. A string literal looks like this:
"I am a string literal".
that on some
machines are stored in a read only memory
String literals are stored wherever the compiler decides
to store them. The 'physical' or operating system-defined
'attributes' of such storage is irrelevant to the language.
The language only states that attempts to modify a string
literal give 'undefined behavior'.
and cannot be modified...
Some platforms might allow such modification, others might
not. Others might crash. Etc. You cannot know from a
language point of view. It's simply 'undefined behavior'.
does
that apply on const char*?
char *literal = "string literal";
/* a pointer-to-char, initialized with the address
of the first character of the literal "string literal" */
char array[] = "Hello world";
/* an array of twelve characters */
char *p = array;
/* a pointer-to-char, initialized with the address of the
first character of the array named 'array'. */
const char *pc = array;
/* a pointer-to-const-char, initialized with the address of the
first character of the array named 'array'. */
*p = 'X'; /* Change what 'p' points to, OK */
*pc = 'X'; /* Change what 'pc' points to, Error, 'pc' points to
const char */
p = literal; /* assign to 'p' the address of the first character
of the string literal */
pc = literal; /* assign to 'pc' the address of the first character
of the string literal */
*p = 'X'; /* Undefined behavior, tries to modify string literal */
*pc = 'X'; /* Undefined behavior, tries to modify string literal */
Whch C book(s) are you reading? Perhaps you need better ones.
See
www.accu.org for peer reviews.
-Mike