views:

125

answers:

3

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
The question is not very clear; You can always get the array length if its definition is local in scope ;-)
dirkgently
@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
+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
"%z" ?? what do you mean?
*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
That macro needs a lot more parentheses to avoid common macro problems.
Tyler McHenry
@Tyler McHenry: Yes, I thought I should add that but then feeling lazy ...
dirkgently
dirkgently
+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.

you can't assume, that you have a pointer from malloc.
fazo
@fazo, you certainly can assume it's from malloc. It's just a terrible idea :)
JaredPar