sizeof "string"

ShanklandJA jas at druxy.UUCP
Thu Feb 2 04:50:43 AEST 1984


A number of incorrect answers to this relatively simple question have
been posted (as well as a roughly equal number of correct ones).  This
is an attempt to clarify the issue.  Please, for those of you who
disagree with what follows, READ THE PERTINENT SECTIONS OF K&R BEFORE
POSTING YET ANOTHER INCORRECT ANSWER TO THE NET!  All page numbers given
below are references to K&R.

Peter Wolfe (mprvaxa!wolfe) says:

    Of course you got the size of a pointer as a result of
    doing sizeof "string".  "string" is in fact a "pointer"
    to a constant string.  I believe that sizeof is the
    only portable way to dtermine [sic] how large data types
    (eg. char's) are in C.

And Greg Woods (hao!woods) says:

    Of course it isn't a good idea to use sizeof on strings!
    It should properly return the size of a char pointer.
    That is why "strlen" is in the stdio library!

And Jack Waugh (rlgvax!jack) says:

    I have seen at least one compiler (I forget which)
    that  gave 2  (the  size  of a pointer on that
    machine) as the size of a string.  So it isn't a
    reliable  portable  practice  to  use sizeof on
    strings.

Folks, "string" is NOT in fact a pointer to a constant string.  "string"
has type array of char and storage class static (pg. 181).  When a
string is referenced in an expression, it, like any other array,
is converted to a pointer to the first element of the array (pp. 94, 185).
But sizeof, when applied to an array, yields the size of the array (pg. 188).
sizeof the array "hello, world" is 13:  enough room for the 12 characters
in quotes plus a terminating '\0', which is what the compiler initializes
the array to.

Yes, sizeof is the only portable way to determine how large data types
are, but that has nothing to do with the question at hand.

strlen's presence in the stdio library has nothing to do with sizeof;
strlen returns the size of a particular string:  in essence, the distance
in bytes from the pointer it is passed to the first occurrence of
a null character ('\0').  strlen is a function called at run-time;
sizeof is resolved at compile time.  strlen( "hello\0, world" ) will
return 5 (note the \0 in the middle); sizeof( "hello\0, world" ) should
be compiled to the constant 14.

Finally, the fact that one C compiler somewhere said that
sizeof( "hello, world" ) was 2 does not mean much; that is just a
compiler bug.  Saying that therefore, using sizeof( <string> ) is
not reliable portable practice makes as much sense as saying that
using the '+' operator is not reliable portable practice because
someone once wrote a C compiler that incorrectly implemented addition.

Jim Shankland
..!ihnp4!druxy!jas



More information about the Comp.lang.c mailing list