-3

int x;x=1; works the same as int x=1;

but

 char str[20];
 str="my name is bla bla";

does NOT work, whereas char str[20]="my name is bla bla"; works

Working on Code block with TDM-GCC-64 compiler

Nathan Fellman
  • 122,701
  • 101
  • 260
  • 319
Sahil
  • 119
  • 6
  • got my answer, thank you. – Sahil Jan 29 '18 at 01:34
  • When programming in C, you need a thorough understanding of the pointer concept. And your `str` symbol can be seen as a char pointer constant, the literal string is a constant char pointer, so the assignment is type-correct, but you're trying to assign something to a constant, which is of course impossible. – Ralf Kleberhoff Jan 29 '18 at 09:45

1 Answers1

4

In C language strings are just arrays of characters. One can say that the core language itself is not even aware of the existence of strings - it is a library-level concept. (With the exception of string literals, perhaps, which are core language feature and which are strings.). In all respects strings are just arrays.

In C language naked arrays are generally not copyable, neither in assignment contexts nor in initialization contexts. Instead, arrays in C instantly decay to pointers with the exception of a few special contexts:

  1. Unary & operator
  2. sizeof operator
  3. _Alignof operator
  4. Initialization of a char[] array with a string literal (in which case array copying actually takes place)

Your example with initialization belongs to the above list, which is why it works. But your example with assignment is not an exception. In the latter case the general rule for array is applied: you can't assign arrays in C. In you want to copy a naked array, you have to use user-level or library-level code.

AnT stands with Russia
  • 312,472
  • 42
  • 525
  • 765
  • 2
    The important thing that's missing from this answer is that C doesn't really have strings. It has arrays of `char`. That's why all the limitations that apply to arrays also apply to strings. – Nathan Fellman Jan 29 '18 at 06:09
  • @NathanFellman Or that C really does have _strings_ - in its standard library, just not as defined by other languages. – chux - Reinstate Monica Feb 07 '18 at 22:32