0

I really do not understand why the function and the calculation in main does not give the same answer.

The function prints 1 and the calculation in main prints 8 - the correct size:

#include <stdio.h>

void size(const int a[]) {
  printf("%i\n",sizeof(a) / sizeof(a[0]));
}

 int main(void) {
  int array[] = { 5, 2, 4, 6, 1, 7, 3, 3 };
  printf("%i\n", (sizeof(array) / sizeof(array[0])));
  size(array);
  return 0;
}
Ardent Coder
  • 3,777
  • 9
  • 27
  • 53
  • Does this answer your question? [How to find the 'sizeof' (a pointer pointing to an array)?](https://stackoverflow.com/questions/492384/how-to-find-the-sizeof-a-pointer-pointing-to-an-array) – ad absurdum Mar 20 '20 at 18:50
  • Also see [finding-length-of-array-inside-a-function](https://stackoverflow.com/questions/17590226/finding-length-of-array-inside-a-function) and [c-sizeof-a-passed-array](https://stackoverflow.com/questions/5493281/c-sizeof-a-passed-array) – ad absurdum Mar 20 '20 at 18:51

1 Answers1

2

You get an incorrect size inside that function because of array decay.

Your array becomes a pointer when you pass it to a function and sizeof(pointer) / sizeof(arr[0]) will give you 1 because in your current architecture configuration, size of a pointer is 4 bytes and size of an integer is also 4 bytes.

But that's not the case when you deal with the original array inside your main function, so you get the correct output there.

S.S. Anne
  • 15,171
  • 8
  • 38
  • 76
Ardent Coder
  • 3,777
  • 9
  • 27
  • 53
  • 2
    That's not the best link. Usually GeeksForGeeks presents incorrect examples or things that "work" but have undefined behavior. – S.S. Anne Mar 20 '20 at 14:54
  • 1
    @S.S.Anne I know, I link gfg when I feel that the OP is a beginner :P Anyways, since you have a decent reputation, feel free to edit my answer :) I'm having a bad day on SO lol – Ardent Coder Mar 20 '20 at 15:33
  • 1
    ... and I agree with you both :) – Luis Colorado Mar 25 '20 at 17:52