tags:

views:

411

answers:

4

Does this...

char* myString = "hello";

... have the same effect as this?

char actualString[] = "hello";
char* myString = actualString;
+2  A: 

No. In the first one, you can't modify the string pointed by myString, in the second one you can. Read more here.

Eli Bendersky
+22  A: 

No.

char  str1[] = "Hello world!"; //char-array on the stack; string can be changed
char* str2   = "Hello world!"; //char-array in the data-segment; it's READ-ONLY

The first example creates an array of size 13*sizeof(char) on the stack and copies the string "Hello world!" into it.
The second example creates a char* on the stack and points it to a location in the data-segment of the executable, which contains the string "Hello world!". This second string is READ-ONLY.

str1[1] = 'u'; //Valid
str2[1] = 'u'; //Invalid - MAY crash program!
BlueRaja - Danny Pflughoeft
I am assuming you meant `char str1[]` instead of `char[] str1`.
Alok
OMG you are right, my entire life is a sham.
BlueRaja - Danny Pflughoeft
this is why some compilers warn you, unless you write `const char* blah="blahblah"`
gnud
[This answer](http://stackoverflow.com/questions/349025/is-a-string-literal-in-c-created-in-static-memory/349030#349030) explains the reasoning behind this.
Lazer
+3  A: 

No. The first one gives you a pointer to const data, and if you change any character via that pointer, it's undefined behavior. The second one copies the characters into an array, which isn't const, so you can change any characters (either directly in array, or via pointer) at will with no ill effects.

Pavel Minaev
+2  A: 

It isn't the same, because the unnamed array pointed to by myString in the first example is read-only and has static storage duration, whereas the named array in the second example is writeable and has automatic storage duration.

On the other hand, this is closer to being equivalent:

static const char actualString[] = "hello";
char* myString = (char *)actualString;

It's still not quite the same though, because the unnamed arrays created by string literals are not guaranteed to be unique, whereas explicit arrays are. So in the following example:

static const char string_a[] = "hello";
static const char string_b[] = "hello";
const char *ptr_a = string_a;
const char *ptr_b = string_b;
const char *ptr_c = "hello";
const char *ptr_d = "hello";

ptr_a and ptr_b are guaranteed to compare unequal, whereas ptr_c and ptr_d may be either equal or unequal - both are valid.

caf