Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Possible Duplicate:
length of array in function argument

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

like image 212
DNB5brims Avatar asked Sep 03 '10 15:09

DNB5brims


People also ask

How do you find the length of an array of a pointer?

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.

How do I get the size of a pointer in C++?

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.

What is array length ()?

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.

How long is an array in C?

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.


2 Answers

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

like image 123
JaredPar Avatar answered Oct 08 '22 14:10

JaredPar


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.

like image 21
dirkgently Avatar answered Oct 08 '22 14:10

dirkgently