Go Back   PACEDev Forums > Blogs > Chris
Blogs FAQ Members List Calendar Search Today's Posts Mark Forums Read

Rate this Entry

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!

Quote:
int foo[12];
printf("sizeof(foo): %d\n", sizeof(foo));
printf("sizeof(foo-1): %d\n", sizeof(foo-1));
Returns:
Quote:
sizeof(foo): 48
sizeof(foo-1): 4
Peculiar!

When we try:
Quote:
printf("&foo: %p\n", &foo);
printf("&(foo-1): %p\n", &(foo-1));
We get:
Quote:
&foo: 0022FF40
&(foo-1): 0022FF3C
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-Þ
Posted in Software
Comments 0 Email Blog Entry
Total Comments 0

Comments

 
Recent Blog Entries by Chris

All times are GMT. The time now is 09:16 PM.


Powered by vBulletin® Version 3.6.8
Copyright ©2000 - 2010, Jelsoft Enterprises Ltd.