0

y is an array of integers with 10 members (size=40 Bytes) but when I pass it to my_function() as x , x has 10 members but if I try to get it's size (sizeof(x)) I will get 8 Bytes as result.

Could you please explain why this happens ?

void my_function(int x[]) {
  printf("%d\n", sizeof(x)/sizeof(x[0]));
}

int main() {

  int y[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
  printf("%d\n", sizeof(y)/sizeof(y[0]));  // Output : 10
  my_function(y);  // Output : 2

  return 0;
}

Ali
  • 3
  • 3
  • 1
    my_function() just gets a pointer to an integer which is 8 bytes on your system. It has no way of knowing the size of the structure it is pointing to. – jmq Oct 09 '19 at 19:40
  • @jmq - What is that integer ? the address of array ? – Ali Oct 09 '19 at 19:44
  • `sizeof` shows the size of the *type*, not the data sent in. The type doesn’t have size of the array so it is just a pointer and there’s no size information available. You always need to give the size to the function separately – Sami Kuhmonen Oct 09 '19 at 19:45
  • @SamiKuhmonen Thanks – Ali Oct 09 '19 at 19:47

1 Answers1

0

Arrays decay to pointers when passed as function parameters, so in my_function the statement printf("%d\n", sizeof(x)/sizeof(x[0])); is equivalent to printf("%d\n", sizeof(int*)/sizeof(int));. On your machine and with your compiler, the size of the pointer is equal to twice the size of an int.

mnistic
  • 10,866
  • 2
  • 19
  • 33