I've been experimenting with arrays, and I have just found the simple way to find the length of an array. I attempted to make this a function with the specific array as the only argument. It didn't work. I thought it was bad coding; but, after a while, I got fed up and put the same code in both the main() and the function. Like so
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.
Code:
int getLength(int *myarray);
int main(void)
{
int myarray[]={5,4,3,2,1};
int size1=(sizeof(myarray) / sizeof(myarray[0]));
int size2=int_getLength(myarray);
printf("%d and %d should be the same",size1,size2);
return 0;
}
int getLength(int *myarray)
{
return (sizeof(myarray) / sizeof(myarray[0]));
}
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.
Comment