Array type char[] is not assignable [duplicate]

落花浮王杯 提交于 2019-11-28 20:27:55

You can't assign to an array, only copy to it.

Use strcpy instead, like

strcpy(word, "Jump");

TL;DR answer : An array name is not a modifiable lvalue. So, you cannot use the assignment operator (=) on that.

To copy the content into the array, you need to use strcpy() from string.h (char array) or memcpy() in general.


Now, to elaborate the actual reason behind the error message, quoting C11, chapter §6.5.16, Assignment operators

assignment operator shall have a modifiable lvalue as its left operand.

and then, quoting chapter §6.3.2.1 from the same standard,

A modifiable lvalue is an lvalue that does not have array type, [....]

So, an array name is not a modifiable lvalue hence, you cannot assign anything to it. This is the reason behind the error message.

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.

Use stcpy from <string.h>-

 strcpy(word,"Jump");

And similar for rest of them.

You just can't do word ="Jump". As the contents are modifiable, the arrays themselves are not.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!