-2
#include <iostream>
using namespace std;


int function(int arr [])
{
  int y = sizeof(arr)/sizeof(arr[0]);
  return y;
}

int main ()
{
  int arr[] = {1,2,3,4,5,6};

  int x = sizeof(arr)/sizeof(arr[0]);

  cout <<x<<"\n";

  int y=function(arr);

  cout <<y<<"\n";

  return 0;
}
6
  • So what output are you getting? Nov 22, 2014 at 14:17
  • 1
    [] in a function parameter does not mean an array, it means a pointer. Nov 22, 2014 at 14:19
  • @TheParamagneticCroissant - in my opionion, om gupta wants write a function where the calculation of the array length is done via a function and I do not know a way how to do that. I would say, this is not possible, because the calculation is done in the preprocessor. Am I correct?
    – lx42.de
    Nov 23, 2014 at 12:12
  • @Mat how did you add the This question already has an answer here:, I found another very good answer: stackoverflow.com/questions/4162923/…
    – lx42.de
    Nov 23, 2014 at 12:26
  • @lx42.de it's not possible. The calculation is not done by the preprocessor either. Nov 23, 2014 at 13:34

2 Answers 2

1
  int arr[] = {1,2,3,4,5,6};
  int x = sizeof(arr)/sizeof(arr[0]);

In this case arr is an array of 6 int elements. sizeof of an int is 4 bytes, thus sizeof(arr) is 24, divided by sizeof of a single int equals 6.

int function(int arr [])
{
  int y = sizeof(arr)/sizeof(arr[0]);
  return y;
}

In this case arr decays to a pointer to an int. Depending on your platform, sizeof of a pointer might be 4 or 8 bytes.

0

The output will be as follows:

6
1

Explanation:

When you compute x inside the main() function, arr is an array. Therefore, sizeof(arr) returns the size of the whole array in bytes.

int x = sizeof(arr) / sizeof(arr[0]);
// 24 / 4 = 6 (assuming your compiler assigns 4 bytes to an integer)

But when you pass the same to a function, what gets passed as the parameter is the pointer to the array. So, this is essentially like passing int *arr to the function.

Source: C++ Size of Array

1
  • I got 6 and 2 on cygwin: PE32+ executable (console) x86-64, for MS Windows. My integers are 64bit/8 Byte long.
    – lx42.de
    Nov 23, 2014 at 12:19

Not the answer you're looking for? Browse other questions tagged or ask your own question.