0
int mid_square(int z[],int length){
    int i,cnt=3,sum=0;

    if (length%2 == 0) { //even length
        length = (length+1)/2;
    }
    else{ //odd length
        length = length / 2;
    }

    for (i=length-2; i<=length+1; i++) {
        sum+=z[i]*pow(10, cnt);
        cnt--;
    }
    return sum;
}

In this code, I use length as function's local variable.
But I don't want to use the variable length.
What can I do??
Before I used the length = sizeof(z)/4, but length is always same value. (4?? 8?? I can't remember)

Kate
  • 23
  • 1
  • 7
  • It's because when you pass an array to a function, it decays to a pointer. And using `sizeof` on a pointer will return the size of the pointer and not what it points to. – Some programmer dude May 05 '15 at 09:05

2 Answers2

2

Once the array is passed as a parameter to a function it decays to a pointer during the call so there is no way to know the sizeof the array in the function and there has to be a extra parameter specifying the size of the array.

So sizeof(z) in the function will give you sizeof(pointer) and not sizeof(array)

Gopi
  • 19,784
  • 4
  • 24
  • 36
2

You cannot determine the size of an array from a function without using another parameter denoting the size. This is because in the function, the "array" is an int*.

Since it is an int*, the sizeof operator returns the size of an int*, and not the size of the array.

Another way would be to use a global variable that stores the size of the array. This is a bad idea though.

Spikatrix
  • 20,225
  • 7
  • 37
  • 83