0

with string literal declaration like this:

char str[] = "hello";

and this

char *ptr = "hello";

initialisation of ptr with str is possible:

ptr = str;     //valid

but not viceversa:

str = ptr;    //invalid

although str being a char array would hold the address of the first element anyways, then what makes the second case invalid and not the first one?

conjuring
  • 121
  • 16
  • Take a look at [this](https://stackoverflow.com/questions/21972465/difference-between-dereferencing-pointer-and-accessing-array-elements) stackoverflow post. – Michael Bianconi Aug 08 '19 at 18:04

2 Answers2

3

Here

char str[] = "hello";
char *ptr = str; /* valid */

above pointer assignment char *ptr = str; is valid as ptr is pointer and its assigned with str which points to base address of str, and in this case ptr is not a constant pointer i.e it can point to different memory location, hence it can be assigned like ptr = str.

But in below case

char *ptr = "hello";
char str[10] = ptr; /* invalid */

the statement char str[10] = ptr; is not valid as str name itself represents one address and by doing char str[10] = ptr; you are trying to modify the base address of str which is not possible because array is not a pointer.

Achal
  • 11,821
  • 2
  • 15
  • 37
  • A feature that I really wish C would include is to create a modifiable char pointer that points to a modifiable string like in the first example, but in one line. – S.S. Anne Aug 08 '19 at 18:32
1

At very first, the string "hello" actually is an array located somewhere in (immutable!) memory.

You can assign it to a pointer, which is what you do in second example (char* ptr = ...). In this case, the pointer just points to that immutable array, i. e. holds the array's address. Recommendation at this point: Although legal in C (unlike C++), don't assign string literals to char* pointers, assign them only to char const* pointers; this reflects immutability much better.

In the second example, you use the first array (the literal) to initialise another array (str). This other array str (if not provided explicit length, as in the example) will use the first array's length and copy the contents of. This second array isn't immutable any more and you can modify it (as long as you do not exceed its bounds).

Assignment: Arrays decay to pointers automatically, if the context they are used in requires a pointer. This is why your first assignment example works, you assign a pointer (the one the array decayed to) to another one (ptr). Actually, exactly the same as in your second initialisation example, you don't do anything different there either...

But arrays aren't pointers, and pointers never decay backwards to arrays. This is why the second assignment example doesn't work.

Aconcagua
  • 24,880
  • 4
  • 34
  • 59