April 15th, 2013, 09:52 PM
What's up guys,
Quick question. I'm reading a book to brush up on some skills and the topic of pointers, arrays, and pointer decay caught my eye as it relates to the sizeof operator.
The text states that when you pass an array to a function it decays to a pointer (since an array name evaluates to the starting address in memory, i.e. &array). So if in the function you have a parameter that receives an array, and then use the sizeof operator on it, it will return the size of the pointer variable that contains it, like 4 or 8 bytes, rather than the true length of the text content in the array.
But it also says that if you call sizeof on an array (not passing it into a function) it will return the length of the array.
I'm aware that arrays are fixed blocks of memory and don't point anywhere else other than the start of it's first element but I want to know why this is. That is, if you have:
char s = "some text";
char *t = s;
why does sizeof(t) evaluate to the size of a pointer on a given machine whereas sizeof(s) gives the length of the array, if an array name is evaluated as it's starting address anyway (i.e. a pointer).
I'm asking this because on the topic of decay, the book says that when a pointer is assigned an array, some information about the length of that array is lost - so how can sizeof figure out the length?
I'm guessing it has something to do with the determined length of the array at compile time...
April 16th, 2013, 12:40 AM
April 16th, 2013, 10:50 AM
err... because s an array and t is a pointer!? :rolleyes:
For efficiency in parameter passing C was originally defined to pass only primitive types by copy, everything else by reference (a pointer). An array is not a true data type in C, and it has both an address and size, bit only the address is passed as a parameter.
When C was standardised by ANSI, then ISO, the ability to pass structs by copy was added. This provides a method of passing arrays by copy by wrapping them in a struct:
char array ;
int sizeofArrayFn( struct sMyArrayWrapper aw )
return sizeof( aw.array ) ; // returns 10