Size of array is not passed through a function. Example:
int my_getsize(int* ptr)
{
return sizeof(ptr);
}
int main()
{
int arr[100];
printf("%d\n", sizeof(arr)); //output: 400
printf("%d\n", my_getsize(arr)); //output: 4
}
In a 32bit system my_getsize(buf)
returns 4, which is the size of pointer. While sizeof(buf)
returns 400 which is 100 * sizeof(int)
(also 4). The only way to around this is to pass the array size to the function. For example foo(arr, sizeof(arr)/sizeof(arr[0]))
Character arrays are a special case because the string is null-terminated, you can look for the last zero in the array. Note however this will not return the array size which includes the null-terminator. It's the same as strlen
. Example:
size_t my_strlen(char* ptr)
{
size_t iSize = 0;
while (*ptr++) iSize++;
return iSize;
}
For char buf[] = "12345"
, sizeof(buf)
is 6, while strlen(buf)
is 5. Usually you need not worry about optimization with this sort of simple functions because the compiler does it for you.