Reputation: 431
char name[25];
name[] = "abcd";
The code above gives me expression syntax error.
char name[25];
name = "abcd";
The code above gives me an Lvalue Required error.
But following code gives no error:
char name[25] = "abcd";
Can anyone please explain?
Upvotes: 0
Views: 451
Reputation: 311068
If to place semicolons as it is required then this construction
char name[25]; name[]="abcd";
may be rewritten for visibility like
char name[25];
name[]="abcd";
So iy is seen that in the second line there us absent a type specifier that the line would be a valid declaration
char name[25];
char name[]="abcd";
In this line where again there is absent a type specifier for the second identifier
char name[25]; name ="abcd"
and we will rewrite like
char name[25];
char name ="abcd";
then name
has the type char
but is initialized by a string literal instead of one character. So it is evident that name shall be an array or a pointer to char, For example
char name[25];
char name[] ="abcd";
or
char name[25];
char *name ="abcd";
or for example
char name[25];
char name[26] ="abcd";
Of course the names of identifiers shall be different. Otherwise the compiler again will issue an error due to redefinition of the same identifier name in the same scope.
Upvotes: 3
Reputation: 198436
char name[25]
(a declaration of an array) does this:
name
as an array of characters (which is almost but not exactly like char *
) pointing to that memory.char name[25] = "abcd"
(a declaration of an array with an initialiser) does this:
"abcd\0"
name
as an array of characters (which is almost but not exactly like char *
) pointing to that memory.(The case of name[] = "abcd"
is not a syntax supported by C.)
In both cases, one of the critical differences between pointers and arrays is that the target of a pointer can change; the target of an array cannot. I.e. you can never assign anything to name
declared as char[]
above, but you can assign to name
declared as char *
, as follows. char *name; name = "abcd"
(a declaration of a pointer, assignment of a literal character array to a pointer) does this:
"abcd\0"
name
as a pointer to character (which is almost but not exactly like char[]
) pointing to undefined target"abcd\0"
to the variable name
.Upvotes: 3