Ways to write a string of characters

Hi all,

Could someone please shed some light on the following?

I define a string of characters with

char* foo = "pimpalicious";	

Whenever I try to modify a character in this string such as in

foo[2] = 'r';

compiler doesn't complain; however my program crashes when I run it.

Whereas if I write my string as

char st[] = "vulcanologist";

I can modify any character in st without a hitch.

Why this behaviour? What is happening under the hood in these two cases?

Read first: http://www.gotw.ca/gotw/009.htm

Now, "pimpalicious" is clearly in block of memory within Const Data.

'foo' is an automatic variable (in Stack), a pointer that is initialized with the address of that Const Data location. It should preferably be const char * foo.

Which version of compiler and with what options? A more verbose compiler should complain.

'st' is a character array, a 14 bytes block in Stack. It is initialized with "vulcanologist", i.e. those characters are copied into the block. (The Const Data probably has "vulcanologist" to copy from.)

Arrays resemble pointers somewhat, so 'st' kind of holds an address -- to the block in Stack.
In first example foo is a pointer (it should be a const pointer but many compilers left char* able to point to string literals because of compatibility with old code).
It points to string literal which are usually stored in read only memory. When you are trying to change it: invalid access and crash.

In second example st is an array with compiler calculated size, containig copy of string literal and placed on stack. You can change it as any other array.
The first one declares a pointer to a string constant. A string constant is not modifiable.

The second one actually creates an array of size sizeof("vulcanologist"). This is equivalent to char st[13] = "vulcanologist";. But since you didn't specify the size of the array, the compiler automatically calculated this.

If you want the first one to work, do:
char st[] = "pimpalicious"; // Creates an array of char
char* foo = st;
foo[2] = 'r';
Topic archived. No new replies allowed.