Re: G_ARRAY_LENGTH for glib.h?



Kaz Kylheku <kaz@ashi.footprints.net> writes:

> > David Benson <daveb@idealab.com> writes:
> > 
> > > #define G_IS_STATIC_ARRAY(array)  ((void*)&(array) == (void*)&((array[0])))
> > 
> > AFAICT, this will always be true. Perhaps did you mean
> > 
> >  array == &array 
> > 
> > which will be true for static arrays ?
> 
> That expression will always trigger a constraint violation; you still
> need the cast.

I left them for the sake of readability.

> Anyway, the address of the first element of an array is the same as
> the address of the whole array. So this test will work for an array
> regardless of its storage class. Even for dynamically allocated
> arrays.

If you have

char c[20], *e;

Then (c == &c), but (e != &e).

See for yourself :

int main()
{

  char c[20], *e;

  e = malloc(20);

  printf("c : %x, &c : %x &c[0] : %x\n", c, &c, &c[0]);
  printf("e : %x, &e : %x &e[0] : %x\n", e, &e, &e[0]);

  return 0;
}

$ ./a.out
c: bffff5f4, &c : bffff5f4 &c[0] : bffff5f4
e: 80495f0, &e : bffff5f0 &e[0] : 80495f0
 
> What the G_IS_STATIC_ARRAY does is really test whether the item is an
> array or a pointer.

That's what I had understood.

> It should be called:
> 
>     G_IS_ARRAY_TYPE_RATHER_THAN_POINTER(A) ((void *) &(A) == (void *) &(A)[0])
> 
> If it is a pointer, then its address is distinct from the location of the
> first element that it points to.

My mistake : this test works too, mine is just shorter :-).

-- 
					Guillaume.
					http://www.telegraph-road.org



[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]