-3

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

I tried this code:

#include<stdio.h>


int dime(int v[]){
    int i= sizeof v / sizeof *v;
    return i;
}

int main() {
    int v[10]={1,2,3,4,5,6,7,8,9,0};
    int i= dime(v);
    printf("The size of v is %d\n",i);
    return 0;
}

and it gives me that the size is 1, I also tried changing *v to v[0] and it didn't solve the problem... Can anyone help?

BTW don't know if it is useful (maybe just to know the size of an integer), but I'm running Eclipse in a Ubuntu 32-bit virtual machine.

Thank you!

Community
  • 1
  • 1
PL-RL
  • 427
  • 2
  • 7
  • 13

1 Answers1

0

The compiler has no knowledge of an array size when being passed as a pointer, only when being passed explicitly as an array. This would work:

int main() {
    int v[10]={1,2,3,4,5,6,7,8,9,0};
    int i = sizeof(v) / sizeof(*v);
    printf("The size of v is %d\n",i);
    return 0;
}
  • Should be `sizeof(v) / sizeof(int);` – Cratylus Apr 28 '12 at 18:21
  • 3
    @user384706: no. `sizeof(*v)` stays correct when `v` is changed to, say, a `long[10]`. – Fred Foo Apr 28 '12 at 18:22
  • @user384706 No. sizeof(v)/sizeof(int) is more likely to be broken if you change the type from int, say, to char. –  Apr 28 '12 at 18:22
  • Thank you, but is it possible to put this in a function that gives me the length of the array? – PL-RL Apr 28 '12 at 18:23
  • No. You have to maintain a data type for storing the data as well as the array. Consider `struct data { int *values; size_t size };` -- of course now you'll have to write functions to create, modify and free such structures. –  Apr 28 '12 at 18:24
  • So I would define the struct data and then have my function "dime"? – PL-RL Apr 28 '12 at 18:25
  • @H2CO3:My point is that for someone who doesn't know that array is being passed as a pointer as the OP, the `sizeof(v) / sizeof(int);` is easy for him to undestand what is the problem and the solution. I don't think `sizeof(*v)` will get him very far in understanding what's going on (but coding in a general manner is a good thing I agree) – Cratylus Apr 28 '12 at 18:44
  • But if won't be usefult either, as the compiler won't have a clue about the size of the array. –  Apr 28 '12 at 18:48