#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;
}
Asked
Active
Viewed 83 times
-2

Hristo Iliev
- 72,659
- 12
- 135
- 186

Om Prakash Kumar
- 51
- 1
- 6
-
So what output are you getting? – striving_coder Nov 22 '14 at 14:17
-
1`[]` in a function parameter does not mean an array, it means a pointer. – The Paramagnetic Croissant Nov 22 '14 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 '14 at 12:12
-
@Mat how did you add the `This question already has an answer here:`, I found another very good answer: http://stackoverflow.com/questions/4162923/calculate-length-of-array-in-c-by-using-function – lx42.de Nov 23 '14 at 12:26
-
@lx42.de it's not possible. The calculation is not done by the preprocessor either. – The Paramagnetic Croissant Nov 23 '14 at 13:34
-
@lx42.de, the message at the top is automatically added by Stack Overflow when the question is closed for being a duplicate of another one. – Hristo Iliev Nov 24 '14 at 14:32
2 Answers
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.

Jiří Pospíšil
- 14,296
- 2
- 41
- 52
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

Community
- 1
- 1

pradeepcep
- 902
- 2
- 8
- 24
-
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 '14 at 12:19