user12184817
user12184817

Reputation:

Why does changing a pointer to a string's value to another string work, but not directly changing a string´s value?

This works

char *pointer1="someString"; //creates a pointer to an array of chars(string) and also the string itself.
pointer1="anotherString";

But this doesn't

char array1[]="someWords and stuff!"; //creates an array of chars(string) with 21 of size(20 for the string itself and 1 for the null character).
array1="anotherString";

Why?

Upvotes: 2

Views: 37

Answers (2)

ProXicT
ProXicT

Reputation: 1933

That's because arrays are not the same as pointers, although arrays are implicitly convertible to pointers. Not the other way around though.

In your first example, the pointer is just pointing to an array of characters.
You can always make the pointer to point to a different address.

In your second example, however, you have an array and in order to access the array, you have to dereference an element of the array and like that you can alter the array. But unlike with pointers, you can't make the array to point to a different array, because it's not a pointer, but the actual storage.

To make it even clearer, in your first example, you're not actually changing the array, you're creating a new array and making the pointer point to the new array instead of the previous one.

Upvotes: 2

tdao
tdao

Reputation: 17668

char array1[]="someWords and stuff!"; //creates an array of chars(string) with 21 of size(20 for the string itself and 1 for the null character).
array1="anotherString";

This doesn't work because the name of the array (array1) is the address of the first array element. In other word, it can be thought of as a constant pointer. After you declare it, it points to a fixed address (of the initial string). You cannot then point array1 to somewhere else.

Upvotes: 0

Related Questions