4

Possible Duplicate:
What is the difference between char s[] and char *s in C?

What is the difference between this:

char arr[] = "Hello, world!";

And this:

char *arr = "Hello, world!";

Where do both strings' memory get allocated? Why am I not able to change content of latter string?

Community
  • 1
  • 1
teacher
  • 1,005
  • 3
  • 15
  • 27
  • 3
    Strictly speaking, the latter should read `const char *arr = "hello world!";` – Nemo Sep 14 '11 at 04:39
  • 1
    @Nemo: It *should*, but strictly speaking C doesn't require it. C string literals are not `const`, but attempting to modify one is undefined behavior – Keith Thompson Sep 14 '11 at 05:25
  • 1
    @teacher: This question has been asked many times on SO. A quick search gave these links. (a) http://stackoverflow.com/questions/1704407/what-is-the-difference-between-char-s-and-char-s-in-c (b) http://stackoverflow.com/questions/1880573/c-difference-between-char-var-and-char-var – Bhaskar Sep 14 '11 at 08:02

1 Answers1

5

The first one is writable memory allocated specifically for arr, which is an array of chars. You can modify it without invoking undefined behavior. This is completely legal:

char arr[] = "Hello, world!";
arr[1] = 'i';

The second one is a pointer to a read-only string. Therefore, this is undefined behavior:

char *parr = "Hello, world!";
parr[1] = 'i'; // Cannot write to read-only memory!

In some compiler implementations:

char *a = "Hello, world!";
char *b = "Hello, world!";

a[1] = 'i';
// b[1] == 'i';

This isn't guaranteed - I'm only including it to give you an 'intuitive' feel of why it's undefined behavior.

Mateen Ulhaq
  • 24,552
  • 19
  • 101
  • 135