Difference between string created by array and pointer?

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 is the memory of both lines allocated? Why can't I change the contents of the last line?

+4
source share
1 answer

The first is the writable memory allocated specifically for arr , which is an array of char s. You can change it without invoking undefined behavior. This is completely legal:

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

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

 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 is not guaranteed . I just turn it on to give you an β€œintuitive” idea of ​​why this behavior is undefined.

+5
source

All Articles