Continue to Site

Welcome to EDAboard.com

Welcome to our site! EDAboard.com is an international Electronics Discussion Forum focused on EDA software, circuits, schematics, books, theory, papers, asic, pld, 8051, DSP, Network, RF, Analog Design, PCB, Service Manuals... and a whole lot more! To participate you need to register. Registration is free. Click here to register now.

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.

Part and Inventory Search

Welcome to EDABoard.com

Sponsor

Back
Top