Re: C Strings
- From: Chris Torek <nospam@xxxxxxxxx>
- Date: 4 Mar 2007 08:02:36 GMT
[Regarding the "peculiar" result for
sizeof ("foobar" + 0)
which in this case is 4...]
In article <1172990746.185238.243160@xxxxxxxxxxxxxxxxxxxxxxxxxxxx>
Bill Pursell <bill.pursell@xxxxxxxxx> wrote:
"foobar" + 0 is forcing the compiler to do an implicit cast,
Well, no: there is no such thing as "implicit cast". You mean
"implicit conversion". (This seems picky -- and *is* picky --
but it is a key picky-ness item. The word "cast" in C refers
*only* to that thing you get by putting a type-name in parentheses
in front of an expression; casts are *always* explicit.)
so that
sizeof("foobar" + 0); is the same as
sizeof((char *)"foobar");
More generally, given any array object, we can find a pointer to
the first element of the array with &name[0]:
int arr[4000];
printf("sizeof arr: %lu\n", (unsigned long) sizeof arr);
printf("sizeof &arr[0]: %lu\n", (unsigned long) sizeof &arr[0]);
printf("sizeof (int *): %lu\n", (unsigned long) sizeof (int *));
This will generally print things like:
sizeof arr: 16000
sizeof &arr[0]: 4
sizeof (int *): 4
(on an "ILP32" style machine; an "I32LP64" machine would get 16000,
8, and 8; an "ILP64" machine like a Cray would get 32000, 8, and 8).
Since the subscript operator is defined in terms of the unary *
operator and addition, arr[0] "means" *(arr + 0). Then, since (as
of C99 at least -- though C89 compilers really do this too) the
unary "&" operator simply "cancels out" unary *, the sequence:
&arr[0]
"means":
&*(arr + 0)
which is the same as just:
(arr + 0)
Thus, sizeof (arr + 0) is the same as sizeof &arr[0], which is the
same as the size of a pointer to the first element of the array.
The conversion that happens in "arr + 0" is the one that I like to
call "The Rule" about arrays and pointers in C. (The Rule no longer
works quite as well for C99 as it did for C89, because C99 has one
case of "array rvalues", namely an array that is a member of a
struct that is returned by a fuction. These things existed in C89,
but C89 failed to define how they work, so that you cannot use
them directly, which makes their C89-existence mostly moot.)
--
In-Real-Life: Chris Torek, Wind River Systems
Salt Lake City, UT, USA (40°39.22'N, 111°50.29'W) +1 801 277 2603
email: forget about it http://web.torek.net/torek/index.html
Reading email is like searching for food in the garbage, thanks to spammers.
.
- Follow-Ups:
- Re: C Strings
- From: subramanian100in@xxxxxxxxx, India
- Re: C Strings
- References:
- C Strings
- From: cman
- Re: C Strings
- From: santosh
- Re: C Strings
- From: subramanian100in@xxxxxxxxx, India
- Re: C Strings
- From: Bill Pursell
- C Strings
- Prev by Date: Re: C Strings
- Next by Date: Re: C Strings
- Previous by thread: Re: C Strings
- Next by thread: Re: C Strings
- Index(es):
Relevant Pages
|
Loading