0

Possible Duplicate:
How to find the sizeof(a pointer pointing to an array)

I have the following program that counts the biggest diff between positions in array, but the sizeof function does not print out what expected. when passing the 10 ints big array and i measure it with sizeof it prints out that it is 8 ints long, how come?

#include <stdlib.h>
#include <stdio.h>

int *
measure(int *arr)
{
    int *answer=malloc(sizeof(int)*10);
    answer[0]=0;
    answer[1]=0;
    int size=sizeof(arr)+1;
    printf("%d\n", size);
    int i;
    for(i=0; i<size; i++)
    {
        signed int dif=arr[i]-arr[i+1];
        if(dif<0)
            dif*=-1;
        if(dif>answer[1])
        {
            answer[1]=dif;
            answer[0]=i;
        }
    }  
    return answer;
}

int
main (void)
{
    int arr[10]={77, 3, 89, 198, 47, 62, 308, 709, 109, 932};
    int *ans=measure(arr);
    printf("the biggest dif is %d between nrs %d and %d\n", ans[1], ans[0], ans[0]+1);
    return 0;
}
Community
  • 1
  • 1
patriques
  • 5,057
  • 8
  • 38
  • 48
  • Assuming that you are getting either 4 or 8 for `size` this the expected behavior. Arrays decay to pointers in many, *many* contexts in c and the pointers no longer know the size of the array. – dmckee --- ex-moderator kitten Nov 20 '12 at 00:35

1 Answers1

5

When passed to a function, an array decays into a pointer. So when you use sizeof on it, it'll give you size of the pointer, not the size of original array you passed.

You can pass another parameter with the size Or use the array's first or last element to store the size information.

P.P
  • 117,907
  • 20
  • 175
  • 238