Quoting Randy Kramer <[EMAIL PROTECTED]>:

> Can anybody help me understand the following statement, or more
> specifically,
> the "(textBuffer *)" part:
>
> buf = (textBuffer *)XtMalloc(sizeof(textBuffer));
>
> Just as a guess, I'm guessing that it does something like make buf a
> pointer
> to a thingie of type textBuffer, and, in fact the pointer points to the
> address of the memory returned by XtMalloc?
>
> Hmm, can I state that more clearly (or should I wait until confirmation
> that
> it is somewhere close to correct)?  I'll give it a shot: the statement
> makes
> buf a pointer to a portion of memory (returned by XtMalloc) of type
> textBuffer.
>

Pretty close. buf is already a pointer to a textBuffer structure, but
is not pointing to anything in particular before the assignment (I suppose).
So it's got to point at some bit of memory which holds/can hold that
structure. XtMalloc here returns a pointer to such memory, freshly allocated.
The trouble is that the XtMalloc function returns a pointer to characters
(char *) - that makes no difference to the pointer value, but the compiler
only wants to allow buf to take a value which is of type textBuffer *.

The (type)value construct is a cast: when applied to pointers, it tells the
compiler to treat the operand - value - as a pointer of type type. In our
we interpret the returned value of XtMalloc as a pointer to a textBuffer
structure rather than one to a character buffer. The assignment to buf then
becomes an assignment of type-compatible values. (No actual machine code is
generated for this. In C, the return value of a function returning a void *
pointer can be assigned directly to a pointer to any other type as a special
case, to avoid writing these casts - as malloc does; but here XtMalloc returns
char * so the cast is necessary.) In short, you're bending C's type system,
but telling the compiler that you know what you're doing.

Tony
-- 
NEdit Develop mailing list - [email protected]
http://www.nedit.org/mailman/listinfo/develop

Reply via email to