开发者

How to get the C pointer array length? [duplicate]

This question already has answers here: Closed 10 years ago.

Possible Duplicate开发者_StackOverflow中文版:

length of array in function argument

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


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 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜