C: sizeof(array-1)
Posted 5th December 2007 at 11:44 AM by Chris
Wonder what happens when you try to take sizeof on a fixed length array with an offset? Me too!
Returns:
Peculiar!
When we try:
We get:
So clearly the compiler (GCC) is pre(de?)moting the array to a pointer, which seems to be backed up by the general behaviour noted in comp.lang.c FAQ - Arrays and Pointers
As it notes, technically foo[-1] isn't legal because pointer arithmetic is only valid within the allocated array space or so, but my guess would be finding an architecture where this is a real issue (apart from the occasional whacked-out embedded system) is probably about the same odds of finding a working system where byte length != 8 bits!
So now you know.
8-Þ
Quote:
int foo[12];
printf("sizeof(foo): %d\n", sizeof(foo));
printf("sizeof(foo-1): %d\n", sizeof(foo-1));
printf("sizeof(foo): %d\n", sizeof(foo));
printf("sizeof(foo-1): %d\n", sizeof(foo-1));
Quote:
sizeof(foo): 48
sizeof(foo-1): 4
sizeof(foo-1): 4
When we try:
Quote:
printf("&foo: %p\n", &foo);
printf("&(foo-1): %p\n", &(foo-1));
printf("&(foo-1): %p\n", &(foo-1));
Quote:
&foo: 0022FF40
&(foo-1): 0022FF3C
&(foo-1): 0022FF3C
As it notes, technically foo[-1] isn't legal because pointer arithmetic is only valid within the allocated array space or so, but my guess would be finding an architecture where this is a real issue (apart from the occasional whacked-out embedded system) is probably about the same odds of finding a working system where byte length != 8 bits!
So now you know.
8-Þ
Total Comments 0
Comments
Recent Blog Entries by Chris
- House of Ginger (22nd December 2009)
- Phones! Laptops! Internets! Oh my !! (7th December 2007)
- Motion blur (5th December 2007)
- C: sizeof(array-1) (5th December 2007)
- Rainy day (5th December 2007)



