mathcom
mathcom

Reputation: 113

Array name can't be l-value means this?

For example,

I declared variable like this,

char szBuffer[12] = {"Hello"};
char szData[12] = {"Cheese"};

szBuffer = szData;

is error, since szBuffer can't be l-value.

szBuffer has its own address, for example, 0x0012345678, and szBuffer's value is also its address, 0x0012345678.

So I think "array name can't be l-value" means that an array's address and its value have to be equal.

Am I right?

If I'm right, why do they have to be equal?

Upvotes: 2

Views: 474

Answers (4)

Mohit Jain
Mohit Jain

Reputation: 30489

array name can't be l-value

It means an array can not be used as l-value or left hand side of the assignment operator (not to be confused with initialization). An l-value must be modifiable. You can modify the contents of array but not the array itself.

In C you can not assign to arrays. Though you can intialize them.

You should use strcpy(szBuffer, szData) or memcpy(szBuffer, szData, 12).

Also there is no need of {} in the initialization from string literal.

If you insist on using operator =, you need to put your string in a struct because struct object copy is allowed in C.

ex:

struct string {
  char name[12];
};

struct string szBuffer = {"Hello"};
struct string szData = {"Cheese"};

szBuffer = szData;

Upvotes: 5

Tom Karzes
Tom Karzes

Reputation: 24052

An L-value is something that can appear on the left hand side of an assignment. Examples: Scalar variables, array elements, pointer dereferences. An array name is not an L-value in C. Instead, you can do one of two things: (1) a pointer assignment, if you just need a pointer to the array, or (2) an array copy, if you really need to copy the array itself.

Upvotes: 0

Haris
Haris

Reputation: 12270

array name can't be l-value means that array names cannot be used on the left side of an =.

To be more clearer, you need a modifiable l-value on the left side of a =


Arrays are modifiable l-value when they are used with indices like arr[i].

But array name themselves are not, and hence cannot be used on the left side of a =

Upvotes: 0

MikeCAT
MikeCAT

Reputation: 75062

No, it won't mean such a thing.

Array's address isn't value of array in general.

Arrays in expression except for operands of sizeof and unary & operator are automatically converted to pointers to first arguments of that array.

Therefore, the converted pointer is not an l-value and you cannot assign there.

Upvotes: 1

Related Questions