5

Possible Duplicate:
length of array in function argument

Is there any method like the Java can .length from a C point array? Thank you.

Community
  • 1
  • 1
DNB5brims
  • 29,344
  • 50
  • 131
  • 195

3 Answers3

6

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

Community
  • 1
  • 1
JaredPar
  • 733,204
  • 149
  • 1,241
  • 1,454
  • The question is not very clear; You can always get the array length if its definition is local in scope ;-) – dirkgently Sep 03 '10 at 15:20
  • @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 Sep 03 '10 at 15:22
3

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
  • 108,024
  • 16
  • 131
  • 187
  • 3
    *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 Sep 03 '10 at 15:24
  • 2
    That macro needs a lot more parentheses to avoid common macro problems. – Tyler McHenry Sep 03 '10 at 15:29
  • @Tyler McHenry: Yes, I thought I should add that but then feeling lazy ... – dirkgently Sep 03 '10 at 15:31
  • @dirk there is no %z in my K&R2 – user411313 Sep 03 '10 at 15:32
  • 1
    That's from C99. K&R2 is old and a lot of water has since flown under the bridge as they say. Search for a document called n1124.pdf. – dirkgently Sep 03 '10 at 15:35
1

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.

user411313
  • 3,930
  • 19
  • 16