Thread: Pointer Decay

  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Feb 2013
    Rep Power

    Pointer Decay

    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[0]). 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...
  2. #2
  3. Contributed User
    Devshed Specialist (4000 - 4499 posts)

    Join Date
    Jun 2005
    Rep Power
    Perhaps this FAQ will help.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper
  4. #3
  5. Contributing User

    Join Date
    Aug 2003
    Rep Power
    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:

    struct sMyArrayWrapper
        char array[10] ;
    int sizeofArrayFn( struct sMyArrayWrapper aw )
        return sizeof( aw.array ) ;  // returns 10

IMN logo majestic logo threadwatch logo seochat tools logo