Difference between char x[4]={"my"}; and char x[4]; x={"my"}; in C

Status
Not open for further replies.

davyzhu

Advanced Member level 1
Joined
May 23, 2004
Messages
494
Helped
5
Reputation
10
Reaction score
2
Trophy points
1,298
Location
oriental
Activity points
4,436
Difference between char x[4]={"my"}; and char x[4]; x={"my"}; in C

Hi all,

I found
Code:
char x[4]={"my"};
can be compiled.

But
Code:
    char x[4];
    x={"my"};
can not be compiled.

Why?
Any suggestions will be appreciated!

Best regards,
Davy
 

Re: [C] String Problem?

hi,

In first statement you can intialising a string which is perfectly OK with the Compiler, where as the second statement is wrong and would most probably give the error of "Lvalue required..."

when we write x={"my"} ...Note that we are actually trying to overwirte the Base address of the character array x. Which is illegal.

The base address must be retained and can't be modified. Whereas i think
*x = "my"; should work with some compilers. try them out...

bye
 

    davyzhu

    Points: 2
    Helpful Answer Positive Rating
[C] String Problem?

The first one is unconventional (because the curly brackets are unnecessary), but correct because you can initialize the declarator (the variable) with either an assignment-expression or an initializer-list surrounded by curly brackets. {"my"} is an initializer-list with one initializer.

The second one is incorrect because curly brackets aren't allowed around an assignment-expression. Omitting the curly brackets would still be incorrect because then you would by trying to reassign the array x.

If you want to copy a string into a char array, do this: strcpy(x, "my"); and don't forget #include <strings.h>

Don't do *x = "my"; because that would convert the address of string "my" to a char (resulting in garbage), and write it into the first element of array x. Not useful.

Try reading the comp.lang.c FAQ:
https://www.eskimo.com/~scs/C-faq/top.html
It's full of common questions and answers, for example:
https://www.eskimo.com/~scs/C-faq/q8.3.html
 

    davyzhu

    Points: 2
    Helpful Answer Positive Rating
Status
Not open for further replies.
Cookies are required to use this site. You must accept them to continue using the site. Learn more…