Pointer problems

How to find the no. of elements in an array using a pointer

1 Like

I think we can’t.

  • Either you can maintain a counter in C.
  • Or, you can use a STL Container in C++, Eg: , whose size can change dynamically, with their storage being handled automatically by the container.
6 Likes
  1. If you have only a pointer, the answer is no.

std::size_t getsize(int* parray) 
{
   return 0; // Sorry, no way to tell.
}

  1. If you have s statically allocated array, you can determine the number of elements from the arrays name. However, if that is the case, and you don’t use C++ functionality, then most likely there wouldn’t be a need for this in the first place.

int array[10];
std::size_t length = 10; // big surprise, that number is right in the definition!
or:
int array[] = {4,78,3,7,9,2,56,2,76,23,6,2,1,645};
std::size_t length = sizeof(array)/sizeof(int); 

  1. Alternately, use the containers from the STL, e. g. std::array or std::vector. These containers behave very similar to standard arrays, but you can query their size at runtime, no problem.

std::vector<int> array;
array.pushback(2);
array.pushback(7);
array.pushback(344);
array.pushback(45);
array.pushback(89);
array.pushback(28);
std::size_t length = array.size(); // easy!

5 Likes