0

For arrays I currently do this to get their size

int A[] = {1,2,3,4,5};
int size =sizeof(A)/sizeof(A[0]) - 1;

Now when I pass this array to a function that takes in as a ptr for instance.

void funct(int *p)
{
   int size =sizeof(p)/sizeof(p[0]) - 1; //This will not work as p is a pointer
}

Any idea on how to get the maximum size of the ptr ?

Rajeshwar
  • 11,179
  • 26
  • 86
  • 158
  • 2
    You can't. Just use `std::array` or a container. – chris Mar 02 '14 at 18:39
  • 1
    `sizeof(p)` gives you the size of the pointer parameter. No it's not possible, you have to pass the size as an extra parameter. I agree with @chris: `std::array<>` would be appropriate for c++. – πάντα ῥεῖ Mar 02 '14 at 18:39
  • What's with the `- 1` in the size? You'll get `4` for `A` that way. Might as well name it `indexLast` then. – chris Mar 02 '14 at 18:43
  • possible duplicate of [determine size of array if passed to function](http://stackoverflow.com/questions/968001/determine-size-of-array-if-passed-to-function) – fredoverflow Mar 02 '14 at 18:49

2 Answers2

2

It is possible if you change the signature of the function:

template <std::size_t N>
void funct(int (&p)[N])
{
   int size = N - 1;
}

However, you can use this function template only with arrays.

nosid
  • 48,932
  • 13
  • 112
  • 139
1

First of all this expression

sizeof(A)/sizeof(A[0]) - 1

is invalid relative to the calculation of the size of an array

/There must be

sizeof(A)/sizeof(A[0])

Moreover the type of the expression is size_t

So instead of

int size =sizeof(A)/sizeof(A[0]);

it would be better to define size as having type size_t

size_t size =sizeof(A)/sizeof(A[0]);

As for pointers then they do not keep information whether they point only one separate object or point the first object of some sequence including arrays. So usually functions that accept pointers as arguments also define the second parameter that specifies the number of elements that belong to the sequence the first element of which the pointer refers to.

So your function should be declared as

void funct(int *p, size_t n);

The exclusion is character arrays that stores strings. In this case you can determine how many characters in a string stored in the array by using standard function std::strlen However this value differs from the size of the array.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335