As others noted, strings are copied with strcpy() or its variants. In some cases, you can also use snprintf() .
You can only assign arrays the way you want, as part of the structure assignment:
typedef struct { char a[18]; } array; array array1 = { "abcdefg" }; array array2; array2 = array1;
If your arrays are passed to functions, it will be shown that you are allowed to assign them, but this is just an accident of semantics. In C, the array will decay into a pointer type with the address value of the first member of the array, and that pointer will be passed. So, your array parameter in your function is just a pointer. Assignment is just a pointer assignment:
void foo (char x[10], char y[10]) { x = y; puts(x); }
The array itself remains unchanged after returning from the function.
This semantic "decay to pointer value" value for arrays is the reason that assignment does not work. The value l has the type of an array, but the r-value is the type of a decomposed pointer, so the assignment is performed between incompatible types.
char array1[18] = "abcdefg"; char array2[18]; array2 = array1;
As to why the βdecay to pointerβ semantics was introduced, this was to ensure compatibility of the source code with the predecessor of C. You can read C language development for details.
jxh May 20, '13 at 8:50 2013-05-20 08:50
source share