-1

I'm working with some arrays in plain C99 and I need to know their size. Does anyone knows why this is happening:

int function(char* m){
    return sizeof(m) / sizeof(m[0]);
}

int main(){
    char p[100];
    int s = sizeof(p) / sizeof(p[0]);
    printf("Size main: %d\nSize function: %d\n",s,function(p));
    return 0;
}

Output:

Size main: 100
Size function: 8

Thanks!

Casper Beyer
  • 2,203
  • 2
  • 22
  • 35
Pablo
  • 69
  • 5
  • When you pass it as a pointer to the function, sizeof returns sizeof char pointer, not length of the array. – 001 Apr 24 '14 at 14:07
  • this is why the length of an array is often passed as an additional arg in c functions – bph Apr 24 '14 at 14:11

2 Answers2

1

This is happening because sizeof(m) == sizeof(char*), which is 8 on your platform.

When you call function(p), p decays into a pointer and loses its size information.

NPE
  • 486,780
  • 108
  • 951
  • 1,012
1

Arrays decay to pointers at the first chance they get, thus in function all you have is a pointer, which is 8 bytes in your case.

jamessan
  • 41,569
  • 8
  • 85
  • 85
Casper Beyer
  • 2,203
  • 2
  • 22
  • 35