[NB: someone needs to write up a decent FAQ entry about this. Memory
allocation and the distinction between arrays and pointers are
probably the most widely misunderstood aspects of C programming.]

Torbjørn Kristoffersen wrote:

> > This allocates precisely one byte of data for dbQuery. Try
> > 
> >     char dbQuery[1024];
> 
> I replied to this mail too, but then I used char *dbQuery instead.
> What's the difference anyway?

Assuming that dbQuery is a local (automatic) variable in all the
following cases:

        char dbQuery[1024] = "";

allocates an array of 1024 characters on the stack at run time, and
initialises it to the empty string (i.e. sets dbQuery[0] to '\0'). 
dbQuery is effectively a constant (typically it's an offset from the
frame pointer) which equates to the address of the first character.

        char dbQuery[] = "";

is similar, but it only allocates enough memory for the specified
string (i.e. 1 byte).

        char *dbQuery = "";

will allocate one byte of memory at compile time in the .rodata
segment (which holds read-only data such as string literals). It will
also allocate a pointer (i.e. `sizeof(char *)' bytes of data) on the
stack at run time, and initialise that pointer with the address of the
string literal.

In this case, dbQuery refers to the pointer, and &dbQuery would be a
constant (i.e. an offset from the frame pointer).

-- 
Glynn Clements <[EMAIL PROTECTED]>

Reply via email to