LinuxSA Mailing list archives
Index:
[thread]
[date]
[subject]
[author]
[stats]
From: Paul Malcolm Bailey <pmbailey@senet.com.au>
To : <linuxsa@linuxsa.org.au>
Date: Wed, 01 Nov 2000 18:24:16 +1030
C query
Hi.
Since I received such a good response from the list last time I had a C
query, thought I'd try my luck again with this one. It's in regards to
arrays and pointers (yep, the fun stuff!)
The following is legal C code:
char a[] = { 'T', 'h', 'i', 's', ' ',
's', 't', 'r', 'i', 'n', 'g', '\0' };
char b[] = "This string";
That is, a string constant is the same as a char array, and either is an
acceptable way to declare and initialise an array of characters (a
string).
So how come (if they're equivalent) I can do this:
char *p1;
p1 = "One more";
...but this...
char *p2;
p2 = { 'O', 'n', 'e', ' ', 'm', 'o', 'r', 'e', '\0' };
...renders a parse error under gcc? (I'm guessing it's illegal.) I
mean, an array of char is what a string constant is, right? I mean,
apart from the '\0' character at the end of a declared and initialised
char array, a string constant is defined as an array of char, surely?
Worse still, I can do this with a pointer declaration:
char *ptr_str_1 = "Some stuff or other.";
Yet I can't even do this:
int *ptr_int_2 = 45;
(What I'm saying here is that *for only strings* I can combine a pointer
declaration with an assignment, but not for other data types. What
gives?)
So, is there something idiosyncratic or "special" about strings and
pointers, or is it that strings and pointers are so often used together
in C that to declare and initialise a pointer with a string constant
*directly* is there as a convenience measure? (I.e. it just saves a bit
of time.)
I hope I've put all this clearly enough. (Oh, yes, I checked through
the C FAQ but couldn't find a substantive enough answer for this kind of
question.)
R,
Paul.
--
LinuxSA WWW: http://www.linuxsa.org.au/ IRC: #linuxsa on irc.linux.org.au
To unsubscribe from the LinuxSA list:
mail linuxsa-request@linuxsa.org.au with "unsubscribe" as the subject
Index:
[thread]
[date]
[subject]
[author]
[stats]
Return to the LinuxSA Mailing List Information Page