Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
| From | James Kuyper <jameskuyper@verizon.net> |
|---|---|
| Newsgroups | comp.lang.c |
| Subject | Re: What's wrong with this simple code? |
| Date | 2012-03-26 13:52 -0400 |
| Organization | A noiseless patient Spider |
| Message-ID | <4F70ACDA.9040902@verizon.net> (permalink) |
| References | <48d7ec09-3c0d-4e4a-9c95-3479417fbf34@x5g2000pbl.googlegroups.com> |
On 03/26/2012 12:28 PM, fajar96te wrote:
> When I tried to compile this:
>
> // ==============
> #include <stdio.h>
> void main()
> {
> char k[4] ;
> k = "abc" ;
> }
> // ==============
>
> I got:
> error: incompatible types when assigning to type 'char[4]' from type
> 'char *'
>
> I'm using gcc on MinGW and Windows 7.
>
>
> What's going on?
Other people have answered your question fairly completely, but no one
seems to have mentioned one of the two main alternative ways of fixing
your code:
const char *k;
k = "abc";
The string literal "abc" calls for allocation of an unnamed array of
char with four elements; the string literal itself is automatically
converted to a char* pointer to the first element of that array. Despite
the fact that it's a char*, rather than a const char*, it's undefined
behavior if your program tries to write to that array. This is because
'const' wasn't added to the language until long to Therefore, it's safer
to store the pointer in a const char*.
If you need to modify the array after creating it, don't use this
method. Use
char k[] = "abc";
instead.
Back to comp.lang.c | Previous | Next — Previous in thread | Next in thread | Find similar | Unroll thread
What's wrong with this simple code? fajar96te <fajar.suryawan@gmail.com> - 2012-03-26 09:28 -0700
Re: What's wrong with this simple code? blp@cs.stanford.edu (Ben Pfaff) - 2012-03-26 09:45 -0700
Re: What's wrong with this simple code? Jens Gustedt <jens.gustedt@loria.fr> - 2012-03-26 18:45 +0200
Re: What's wrong with this simple code? "BartC" <bc@freeuk.com> - 2012-03-26 17:45 +0100
Re: What's wrong with this simple code? jt@toerring.de (Jens Thoms Toerring) - 2012-03-26 16:50 +0000
Re: What's wrong with this simple code? James Kuyper <jameskuyper@verizon.net> - 2012-03-26 13:52 -0400
Re: What's wrong with this simple code? nick_keighley_nospam@hotmail.com - 2012-03-29 00:16 -0700
Re: What's wrong with this simple code? fajar96te <fajar.suryawan@gmail.com> - 2012-03-28 17:23 -0700
Re: What's wrong with this simple code? Sjouke Burry <s@b> - 2012-04-02 20:39 +0000
Re: What's wrong with this simple code? "BartC" <bc@freeuk.com> - 2012-04-02 22:07 +0100
csiph-web