In C, one can use a string literal in a declaration like this:
char s[] = "hello";
or like this:
char *s = "hello";
So what is the difference? I want to know what actually happens in terms of storage duration, both at compile and run time.
ccharconstantsstring
In C, one can use a string literal in a declaration like this:
char s[] = "hello";
or like this:
char *s = "hello";
So what is the difference? I want to know what actually happens in terms of storage duration, both at compile and run time.
Best Answer
The difference here is that
will place
"Hello world"
in the read-only parts of the memory, and makings
a pointer to that makes any writing operation on this memory illegal.While doing:
puts the literal string in read-only memory and copies the string to newly allocated memory on the stack. Thus making
legal.