The =
operator cannot be used to copy the contents of one array to the other; you must use a library function like strcpy
or strcat
for strings, memcpy
for non-strings (or assign array elements individually).
This is a consequence of how C treats array expressions. An array expression is defined by the language standard to be a non-modifiable lvalue; it's an lvalue because it refers to an object in memory, but it may not be the target of an assignment.
The array subscript operation a[i]
is defined as *(a + i)
; that is, given the array address a
, offset i
elements from that address and dereference the result. Since the array expression a
is treated as a pointer, most people think a
variable stores a pointer to the first element of the array, but it doesn't. All that gets stored are the array elements themselves.
Instead, whenever the compiler sees an array expression in a statement, it converts that expression from type "N-element array of T
" to "pointer to T
", and the value of the expression becomes the address of the first element of the array (unless the expression is the operand of the sizeof
or unary &
operators, or is a string literal being used to initialize another array in a declaration).
And this is why an array expression like word
cannot be the target of an assignment; there's nothing to assign to. There's no object word
that exists independently of word[0]
, word[1]
, etc.
When you write
word = "Jump";
the type of the expression "Jump"
is converted from "5-element array of char
" to "pointer to char
", and the value of the expression is the address of the first element of the array. And you're trying to assign that pointer value to an array object, which a) isn't a pointer, and b) cannot be assigned to anyway.
word
withoutstrcpy
you can makeword
typed likeconst char *word
. – Encipher