From: Glynn Clements <glynn.clements@virgin.net>
To: linux-c-programming@vger.kernel.org
Subject: Re: const char * vs char[]
Date: Tue, 23 Mar 2004 20:26:47 +0000 [thread overview]
Message-ID: <16480.40327.998566.932705@cerise.nosuchdomain.co.uk> (raw)
In-Reply-To: <20040323170446.GB11933@lug-owl.de>
Jan-Benedict Glaw wrote:
> > No... "char*" and "char []" are synonyms.
>
> There's a subtle difference:
I wouldn't say that the difference between pointers and arrays is
subtle; the difference is actually rather substantial.
The reason why beginners tend to confuse the two is that C treats an
array as a pointer to its first element in almost all of the
situations where an array can be used.
> char *hello_ptr = "A really loooong hello world";
> char write_string[] = "this is some long garbage";
>
> void main(void) {
> /* legal */
> sprintf (write_string, "%s", "stuff");
>
> /* illegal - may be in a read-only segment */
> sprintf (hello_ptr, "%s", "Don't do that");
> }
>
> So if you're preparing some space for say building up some packet (to be
> sent out to hardware), use "char xx[]", but if you only want to have a
> read-only string (to printf() it to the user), you can use "char *xx".
In the latter case, you could also use "const char xx[]".
The main reasons to make a variable a pointer rather than an array
are:
1. You want the pointer to point at some pre-existing data.
2. You want to be able to change the pointer itself (as opposed to
what it points at).
--
Glynn Clements <glynn.clements@virgin.net>
next prev parent reply other threads:[~2004-03-23 20:26 UTC|newest]
Thread overview: 8+ messages / expand[flat|nested] mbox.gz Atom feed top
2004-03-23 12:01 const char * vs char[] Massimiliano Cialdi
2004-03-23 12:19 ` Glynn Clements
2004-03-23 13:44 ` Mariano Moreyra
2004-03-23 14:19 ` Massimiliano Cialdi
2004-03-23 14:52 ` Mariano Moreyra
2004-03-23 17:04 ` Jan-Benedict Glaw
2004-03-23 20:26 ` Glynn Clements [this message]
2004-03-23 20:37 ` Glynn Clements
Reply instructions:
You may reply publicly to this message via plain-text email
using any one of the following methods:
* Save the following mbox file, import it into your mail client,
and reply-to-all from there: mbox
Avoid top-posting and favor interleaved quoting:
https://en.wikipedia.org/wiki/Posting_style#Interleaved_style
* Reply using the --to, --cc, and --in-reply-to
switches of git-send-email(1):
git send-email \
--in-reply-to=16480.40327.998566.932705@cerise.nosuchdomain.co.uk \
--to=glynn.clements@virgin.net \
--cc=linux-c-programming@vger.kernel.org \
/path/to/YOUR_REPLY
https://kernel.org/pub/software/scm/git/docs/git-send-email.html
* If your mail client supports setting the In-Reply-To header
via mailto: links, try the mailto: link
Be sure your reply has a Subject: header at the top and a blank line
before the message body.
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for NNTP newsgroup(s).