On Tue 2008-02-12 16:24:20 UTC-0000, John Matthews ([EMAIL PROTECTED]) wrote:

> Hi- in C, is it guaranteed that
> 
>   (unsigned)&ptr[1] - (unsigned)&ptr[0] == sizeof ptr[0]

Note that on some systems

  sizeof(void *) > sizeof(unsigned) == 1

There is an integer type defined in the C standard named ptrdiff_t
(declared in stddef.h) which you should use, so your expression
becomes:

  (ptrdiff_t) &ptr[1] - (ptrdiff_t) &ptr[0] == sizeof ptr[0]

This may be a bit academic as you're probably unlikely to be
subtracting pointers very often in ordinary programs, let alone
typecasting pointers to an their offsets, then subtracting the
offsets.  :-)

> and hence that
> 
>   ptr = malloc(n * sizeof ptr[0]);

You can rewrite this as:

  ptr = malloc(n * sizeof *ptr);

But both are valid.

> will (attempt to) allocate enough memory for ptr[0..n-1] ?
> Or do you have to allow for possible padding etc.?

There is no padding.  All blocks of memory allocated with malloc() are
contiguous as far as the program is concerned.

This may not actually reflect how those blocks of memory are stored on
the hardware.  What appears as contiguous memory in your C program may
be fragmented (non contiguous) on the hardware itself, but the
fragmentation is completely invisible to the program.  malloc() does a
lot of magical things behind the scenes to make this happen.  :-)

Reply via email to