C Array length function problem - C / C++
return 0;
}
int getLength(int *myarray)
{
return (sizeof(myarray) / sizeof(myarray[0]));
}
size1,main, prints to be 5, which is the correct length.
size2, function, prints 1.
I don't know why this is happening. I have also tried using (int myarray[])as the parameter, but the output is the same.
My logical assumption would be that the function is only passing in the first element of the array or it could do something with obtaining the length. Can someone please explain why this is happening.
When single dimension array is passed as a parameter to a function then it is passed as a pointer.
Thats why u are getting the size like that
Raghuram
Feb 9 '08
#2
reply
weaknessforcats
Expert Mod 5K+
P: 6,832
weaknessforcats
The real problem is a thing called decay of array.
That is, when an array is passed to a function, all that is passed is the address of element 0. So the function gets and address and not the entire array. From the perspective of the function, the array has disappeared and all the function sees is a pointee to a single vaiable. The function must assume there is an array.
Then, the sizeof only tells you the size of the variable on the local stack. In this case, the size of the address, which is most likely 4.
So, don't use that sizeof trick to get the number of array elements. Instead define a const int that is set to the number of elements and pass that along withe the array name to the function.
Feb 9 '08
#3
reply
2n2is5
P: 2
2n2is5
The real problem is a thing called decay of array.
That is, when an array is passed to a function, all that is passed is the address of element 0. So the function gets and address and not the entire array. From the perspective of the function, the array has disappeared and all the function sees is a pointee to a single vaiable. The function must assume there is an array.
Then, the sizeof only tells you the size of the variable on the local stack. In this case, the size of the address, which is most likely 4.
So, don't use that sizeof trick to get the number of array elements. Instead define a const int that is set to the number of elements and pass that along withe the array name to the function.
I had assumed that was the only way, Thanks.