Decay

Pointer Decay

Here is an example of an array decaying to a pointer when it is passed to a function

#include <iostream>
using namespace std;

//example of array decaying to a pointer when passed to a function
void init(int a[] ){ // array decays to a pointer
    cout << "In func init" <<endl;
    cout << sizeof(a) <<endl; //8
    cout << sizeof(a[0]) <<endl; //4
    size_t s= sizeof(a)/sizeof(a[0]);
    cout  << s << endl; //2
    // On 64 bit OS's
    // a pointer is 64 bits (8 bytes) and an int is 32 bits (4 bytes)
    //for (int x=0; x<s; x++)
    //cannot iterate over array since size is unknown
}

//proper way of passing a C array. We must also pass the size
void propinit(int *a, size_t s ){
    cout << "in func init2" <<endl;
    for (size_t x=0; x<s; x++)
    {
        a[x]=x;
        cout << a[x] ;
    }
    cout << endl;
}

int main(){
    int a[6];
    cout << sizeof(a) <<endl; //24
    cout << sizeof(a[0]) <<endl; //4 size of int
    size_t s= sizeof(a)/sizeof(a[0]); // 24/4
    cout  << s << endl; //6
    init(a);  //pass array to function init
    propinit(a,6); //pass array and the size
    return 0;
}