0
#include <stdio.h>
int a[3] = {1,2,3};

void cal(int* item){
    printf("Length(inside) is %lu\n", sizeof(item)/sizeof(item[0]));
}

int main(){
    printf("Length(outside) is %lu\n", sizeof(a)/sizeof(int));
    cal(a);
}

The code above comes out with the result that

Length(outside) is 3
Length(inside) is 2

However, it is wrong, because both of them should be 3, what's wrong with my code?

Hanslen Chen
  • 440
  • 1
  • 3
  • 14
  • 2
    The size of a pointer is the size of the pointer, not what is points to. If you need the length of the array, you need to pass it as an argument to the function. – Some programmer dude Mar 29 '16 at 15:36

2 Answers2

0

This is because the array decays into a pointer when it is passed to a function.

So essentially what you are doing is

sizeof(int*)/sizeof(int);

What you can think is the difference between

int a[5];
sizeof(a)/sizeof(a[0]); //this works

and

int a[5];
int* p = a;
sizeof(p)/sizeof(p[0]);
Haris
  • 12,120
  • 6
  • 43
  • 70
0

First of all, you should be using %zu fomat specifier to print the result.

Secondly, when passed to a function as argument, array name decays to the pointer to the first element, so the sizeof(item) will not work as expected.

Basically what you're doing is sizeof (int *)/ sizeof (int) and in your environment, it is likely that a pointer occupies 8 bytes and an int takes 4, so you get this result.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261