Giorgi Cercvadze Giorgi Cercvadze - 3 months ago 28
C Question

Why is not possible to assign a pointer to an array?

In C, I'm coding this

char * real = strdup("GEORGE");
char one[1024];
one = real;

and it gives error:

invalid initializer

any suggestions?
is there any chance I can make array of chars equal to char pointer?


In your code, one is a variable of type array. Thus,

 one = real;

is attempt to assign to an array type, which is not allowed.

To elaborate, array names are no modifiable lvalues and assignment operator only works on modifiable lvalues as the LHS operand.

Quoting C11, chapter §6.5.16

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

and then, chapter §, (emphais mine)

A modifiable lvalue is an lvalue that does not have array type, does not have an incomplete type, does not have a const qualified type, and if it is a structure or union, does not have any member (including, recursively, any member or element of all contained aggregates or unions) with a const qualified type.

You need to use strcpy() to copy the content to the array.