What is the difference between char s[] and char *s?

user188276 picture user188276 · Nov 9, 2009 · Viewed 352.6k times · Source

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.

Answer

Rickard picture Rickard · Nov 9, 2009

The difference here is that

char *s = "Hello world";

will place "Hello world" in the read-only parts of the memory, and making s a pointer to that makes any writing operation on this memory illegal.

While doing:

char s[] = "Hello world";

puts the literal string in read-only memory and copies the string to newly allocated memory on the stack. Thus making

s[0] = 'J';

legal.