LinuxSA Mailing list archives
Index:
[thread]
[date]
[subject]
[author]
[stats]
From: Michael T Pope <michael.pope@dsto.defence.gov.au>
To : <linuxsa@linuxsa.org.au>
Date: 03 Nov 2000 14:07:04 +1030
Re: C query
Paul Malcolm Bailey <pmbailey@senet.com.au> writes:
> 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.)
As others have remarked, the syntax for array initialization is not valid
for pointer assignment.
> I mean, an array of char is what a string constant is, right?
No, and this is a different misunderstanding. A construct like "One
more" is not an array of char. Its effective type is "const char*",
which can be a problem as the following illustrates---
345 Riesling> cat > foo.c
char* foo = "bar";
int main(void) {
foo[1] = 'A';
return 0;
}
346 Riesling> gcc foo.c
347 Riesling> a.out
Segmentation fault (core dumped)
We may have declared foo to point to char, but we lied, and pointed it
to const char. When we tried to modify what we pointed to, we
deservedly lost. Change the above to "char foo[]" and all is well
again, because then the characters are effectively copied into the
array foo.
> Yet I can't even do this:
>
> int *ptr_int_2 = 45;
You certainly can, especially if that was "(int*) 45". It might even
be meaningful on a machine where 45 is a valid address to store an
int, which is not however the case for most linux boxes. I doubt that
was what you intended to say though. If you mean, you can not do---
int* ptr = { 4, 5 };
---you are quite right. The array syntax is necessary there.
> (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?)
I have tried to avoid saying `string' in this reply. Elsewhere Glen
correctly points out that C really does not have strings. I would
rather say:
char*'s are different in that you can combine declaration with
an initialization to a const char*.
I strongly recommend not using this form of declaration / initialization.
Cheers,
Mike Pope
--
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