sizeof() on constant strings

Scott Lovenberg scott.lovenberg at gmail.com
Tue Sep 2 18:21:09 MDT 2014


On Tue, Sep 2, 2014 at 5:35 AM, Ralph Böhme <rb at sernet.de> wrote:
> On Tue, Sep 02, 2014 at 03:12:57AM -0500, Scott Lovenberg wrote:
>> On Tue, Sep 2, 2014 at 12:18 AM, Andrew Bartlett <abartlet at samba.org> wrote:
>> > Just a hint I found out the hard way recently:
>> >
>> > char *foo = "ba";
>> > and
>> > char foo[] = "ba";
>> > give different results when you do sizeof(foo).  See attached test
>> > program.
>>
>> Stupid question, does compiler matter?
>
> no. What matters is: "what is foo?" !
>
>> > char *foo = "ba";
>
> Here foo is a _pointer_ to char, as such sizeof(foo) yields the
> implementation defined size of a pointer.
>
>> > char foo[] = "ba";
>
> Here foo is an array of char, initialized with the contents of a
> static string. As such sizeof(foo) yields the size of the array.
>
> Cheerio!
> -slow
>
> --
> SerNet GmbH, Bahnhofsallee 1b, 37081 Göttingen
> phone: +49-551-370000-0, fax: +49-551-370000-9
> AG Göttingen, HRB 2816, GF: Dr. Johannes Loxen
> http://www.sernet.de,mailto:kontakt@sernet.de

Oh, right.  That's subtle unless you stop to think about it for a
minute. Thanks for pointing that out!

-- 
Peace and Blessings,
-Scott.


More information about the samba-technical mailing list