Predict the output
#include
#include
void fun(int arr[]) {
cout << sizeof(arr) / sizeof(arr[1]);
}
int main()
{
int arr[10];
cout << sizeof(arr) / sizeof(arr[1])<<endl;
fun(arr);
_getch();
}
Answer: 10 1
The function fun() receives an array parameter arr[] and tries to find out number of elements in arr[] using sizeof operator.
In C, array parameters are treated as pointer.So the expression sizeof(arr)/sizeof(arr[0]) becomes sizeof(int *)/sizeof(int) which results in 1 for IA 32 bit machine (size of int and int * is 4) and the for loop inside fun() is executed only once irrespective of the size of the array. Therefore, sizeof should not be used to get number of elements in such cases. A separate parameter for array size (or length) should be passed to fun().
#include
void fun(int arr[]) {
cout << sizeof(arr) / sizeof(arr[1]);
}
int main()
{
int arr[10];
cout << sizeof(arr) / sizeof(arr[1])<<endl;
fun(arr);
_getch();
}
Answer: 10 1
The function fun() receives an array parameter arr[] and tries to find out number of elements in arr[] using sizeof operator.
In C, array parameters are treated as pointer.So the expression sizeof(arr)/sizeof(arr[0]) becomes sizeof(int *)/sizeof(int) which results in 1 for IA 32 bit machine (size of int and int * is 4) and the for loop inside fun() is executed only once irrespective of the size of the array. Therefore, sizeof should not be used to get number of elements in such cases. A separate parameter for array size (or length) should be passed to fun().
Comments
Post a Comment