Rick <[EMAIL PROTECTED]> wrote:
> you wrote:
> > Rick <Mowgli53@> wrote:
> > >
> > > in C:
> > >
> > > #include <stdio.h>
> > > #include <stdlib.h>
<stdlib.h> is not needed.
> > > int main(int argc, char *argv[])
Simplify to...
int main(void)
> > > {
> > > char *s="\12345s\n";
> > > printf("sizeof(s) is %d\n",sizeof(s));
See below.
> > > printf("s= 0x%02x (octal %o), 0x%02X (char %c), 0x%02X" \
The \ is not needed. Note that \ is translated long before
string literals are concatenated.
> > > "(char %c), 0x%02X (char %c) 0x%02X (octal %o)\n",
> > > s[0], s[0], s[1], s[1], s[2], s[2], s[3], s[3], s[4], s[4]);
> > >
> > > system("PAUSE");
I take it you don't like *nix environments. ;)
> > > return 0;
> > > }
> >
> > why do you expect sizeof(s) to be 5?
Good question.
> > s is a char*, not a char[].
Not relevant.
> Doh! You are so right! What was I thinking???
>
> Thank you for waking me up.
Since Nico has got you out of bed, perhaps I can serve some
coffee and toast. ;)
Firstly, char *s="\12345s\n";, is analogous to...
static const char blah[] = { 0123, '4', '5', 's', '\n', 0 };
char *s = blah;
Octal character escapes are limited to 3 digits. The
static string literal reserves 6 characters, not 5.
As an aside, hex (\x) escapes are not bounded to any
number of digits, so...
"\x0dAbout last night!"
...is not the same as...
"\x0d" "About last night!"
It's actually the same as...
"\x0dab" "out last night!"
...where \x0dab is a single character!
To avoid a similar issue to hex escape sequences,
programmers often write \012, rather than \12, not
because an octal escape needs a leading zero (it doesn't),
but because it makes it less likely for problems arising
if the next character is a literal digit that happens to
be an octal digit.
Secondly, sizeof returns a size_t which is an unsigned
type that need not be compatible with %d.
Even on systems where it doesn't crash, your code may
well print "sizeof(s) is 0" for unsurprising reasons.
C99 (and many glibc implementations) support %zu for
printing size_t values. C90 programmers often use
%u or %lu and cast the size_t argument.
--
Peter