Is there any method like the Java can .length from a C point array? Thank you.
+5
A:
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
JaredPar
2010-09-03 15:15:10
The question is not very clear; You can always get the array length if its definition is local in scope ;-)
dirkgently
2010-09-03 15:20:33
@dirkgently, I agree, it's unclear if they're asking for a pointer length or array length. I redirected them to your answer for the latter
JaredPar
2010-09-03 15:22:41
+2
A:
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.
dirkgently
2010-09-03 15:19:44
*z* _Specifies that a following d, i, o, u, x, or X conversion specifier applies to a `size_t` or the corresponding signed integer type argument; or that a following n conversion specifier applies to a pointer to a signed integer type corresponding to size_t argument._
dirkgently
2010-09-03 15:24:40
That macro needs a lot more parentheses to avoid common macro problems.
Tyler McHenry
2010-09-03 15:29:54
@Tyler McHenry: Yes, I thought I should add that but then feeling lazy ...
dirkgently
2010-09-03 15:31:59
dirkgently
2010-09-03 15:35:45
+1
A:
If you use MSVC/MinGW there is a NONPORTABLE solution for a real C-pointer:
#include <malloc.h>
char *s=malloc(1234);
#ifdef __int64
printf( "%lu\n", _msize(s));
#else
#endif
For a real C-Array like
AnyType myarray[] = {...};
or
AnyType myarray[constVal];
see the other answer.