0

Possible Duplicate:
How to find the sizeof(a pointer pointing to an array)

i am passing an array to a function. is there is any way of finding the size of array in that function.

i don't think that sizeof function works as only pointer to first element of the array is passed to the function.

sizeof(arr)/sizeof(arr[0])

i don't think that the above code works. is there any other way...

Thanks...

Community
  • 1
  • 1
Abdul Samad
  • 5,748
  • 17
  • 56
  • 70

4 Answers4

4

Using raw arrays, there's no simple or reliable way to find its size once it is passed as a pointer to a function. (I don't count reading the debug information from the binary as simple, for example.)

In C++, you should probably be using a std::vector<YourType> and then you can find out easily.

In C, you have to ensure you pass the size as well as the pointer.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
2

If your c++ tag is serious, you can use std::vector since it keeps the size information vec.size(). Otherwise you need to pass the size to the function, or have a structure/class keep array and size together.

perreal
  • 94,503
  • 21
  • 155
  • 181
  • `std::array` is a template type (templated on the array size); `std::vector` is resizable at runtime. I suspect that if OP is at a level where these kinds of questions need to be asked, the extra flexibility will be appreciated. – Karl Knechtel Mar 10 '12 at 14:59
  • He meant `std::vector`. `std::array` can be used, when the size is known at the compile time. – Rafał Rawicki Mar 10 '12 at 14:59
  • true, `std::vector` will be easier to use – strcat Mar 10 '12 at 15:00
1

If you only have a pointer to the first element then no, there is no way to know the size of the array. If you really need to know the size, you have a few options;

  • Terminate the array with a value that does not exist in normal data (an example is a \0 as C uses to terminate strings or NULL in a pointer array)
  • Pass the length of the array around with the array.
  • Change to a datatype that knows about size, like std::vector (not an option in C, but you also tagged C++)
  • Create your own struct that can contain size+array pointer and pass that around.
Joachim Isaksson
  • 176,943
  • 25
  • 281
  • 294
0

No, there isn't. That why all sensible functions from the C Standard Library pass a pair of (pointer, size) as parameters. In C++ the convention is to pass two pointers, (start, end) instead, which is almost equivalent.

Roland Illig
  • 40,703
  • 10
  • 88
  • 121