sizeof() on constant strings

Ralph Böhme rb at sernet.de
Tue Sep 2 04:35:16 MDT 2014


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


More information about the samba-technical mailing list