Possible Duplicate:
length of array in function argument
Is there any method like the Java can .length from a C point array? Thank you.
In pointers, you are allowed to find the length of the pointer with the help of len() function. This function is a built-in function returns the total number of elements present in the pointer to an array, even if the specified pointer is nil. This function is defined under builtin.
The size of a pointer in C/C++ is not fixed. It depends upon different issues like Operating system, CPU architecture etc. Usually it depends upon the word size of underlying processor for example for a 32 bit computer the pointer size can be 4 bytes for a 64 bit computer the pointer size can be 8 bytes.
The length property of an object which is an instance of type Array sets or returns the number of elements in that array. The value is an unsigned, 32-bit integer that is always numerically greater than the highest index in the array.
Programming Logic to Calculate the Length of an Array in C Determine the size of a datatype value using the sizeof(datatype). To find the array's length (how many elements there are), divide the total array size by the size of one datatype that you are using.
No, given a C pointer you cannot determine it's length in a platform agnostic manner.
For an actual C array though see dirkgently's answer
You could get it using a macro:
#define sizeofa(array) sizeof array / sizeof array[ 0 ]
if and only if the array is automatic and you access it in the scope of its definition as:
#include <stdio.h>
int main() {
int x[] = { 1, 2, 3 };
printf("%zd\n", sizeofa( x ));
return 0;
}
However, if you only have a (decayed) pointer you cannot get the array length without resorting to some non-portable implementation specific hack.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With