0

I'm creating an integer array whose input will be given by user, and I'm passing it to a function where it is decaying to a pointer(say int * a), now how can I obtain the length of the array in my function using only the available resource, that is the pointer to the first array element?

I have tried "templates"(template) which works on array and not on pointer. I did not want to use "struct"(putting array inside struct and passing the struct to function) as it just avoids the problem. I also did not want to stash the size in one block extra in the array as I did not want to consume more memory than what is required(even though it is a mere one). I also did not want iterators("begin" and "end"), they mostly do not work on pointers. I did not want a C++11 solution or a boost library solution too as I did not want to depend on version or a library.

#include <iostream>
using namespace std;
void func(int *a)
{
 //Now entire programming is to be done here as array has been passed
 //How to find length using pointer a only, so that I can proceed with
 //array operations?
 //This function is not aware of length because of Array Decay but
 //atleast has a starting point that is the pointer.
}
int main()
{
int array[5]={2,3,4,5,6};
func(array);
//main()'s use is over now, control is shifted to void func(int *)
return 0;
}

I expect a method to find length using the pointer only, that is I expect the number 5(length of array) to get generated somehow inside func() method.

Prasanjit Rath
  • 166
  • 2
  • 13
  • 4
    The short answer is: nope, C++ does not work this way. – Sam Varshavchik Jul 28 '19 at 13:46
  • 1
    You are responsible for passing the length of the array to the function. `size_t size = 5; func(array, size);`. And func need to accept that parameter `void func(int* a, size_t size) { ... }`. But much better to use `std::vector` which encapsulates that information. – Eljay Jul 28 '19 at 14:22

1 Answers1

0

No it's not possible. This is one of the many, many reasons that you should normally use std::vector instead of arrays.

Vectors are actually easier, safer, more powerful and more intuitive than arrays. The sooner you learn how to use them the better.

john
  • 85,011
  • 4
  • 57
  • 81
  • Thanks, but can you elaborate on what do you mean by "safer"? – Prasanjit Rath Jul 28 '19 at 14:06
  • Safer because the container manages its size and memory for you. You don't have to worry about memory leaks or remembering to update the size after resizing. There is also the .at() which will tell you when you access an invalid index. http://www.cplusplus.com/reference/vector/vector/at/ – drescherjm Jul 28 '19 at 14:09