0

I am handling a function of type:

 int xyz(int input[])

I do not have access to the main function and therefore have no idea about the size of the array. How can i find the size of the input array? Is there any way to know where the array ends? sizeof(input)/sizeof(int*) is giving 1 as input is basically a pointer.

MOHAMED
  • 41,599
  • 58
  • 163
  • 268
SvckG
  • 55
  • 2
  • 9
  • `sizeof(input)` is equivalent to `sizeof(int *)`. So, `sizeof(input)/sizeof(int*)` will always return `1`. – Bechir Apr 19 '13 at 09:53
  • You can change the function to take additional parameter storing length. Or, you can store sentinel value at the end of array (like null-terminated strings). – milleniumbug Apr 19 '13 at 09:53
  • possible duplicte http://stackoverflow.com/questions/5493281/c-sizeof-a-passed-array – MOHAMED Apr 19 '13 at 09:54
  • 1
    This isn't a duplicate - in this question "I do not have access to the main function and therefore have no idea about the size of the array." so a workaround or possible insight to resolve the issue is needed, whereas the linked question assumes you can just start passing the number of parameters from the caller. – Tony Delroy Apr 19 '13 at 09:59

3 Answers3

5

If the caller doesn't provide the size information about the array then there's no way to get the size in function xyz().

You can pass the size information in another variable (or as an elemnt of the array).

int xyx(int abc[], size_t len)
{

}
P.P
  • 117,907
  • 20
  • 175
  • 238
3

No... there's no (portable) way from within the called function, so it's normal in this situation (i.e. when no number-of-elements parameter is passed) for callers to adopt some convention such as providing a sentinel value in the last used element or guarantee a set number of elements. If a sentinel is used, you might be able to prove to yourself that this was being done by checking the calling code in a debugger.

Tony Delroy
  • 102,968
  • 15
  • 177
  • 252
  • does sizeof(input)/sizeof(int*) reduce to one because "input" is nothing but an integer pointer as well? – Rüppell's Vulture Apr 19 '13 at 09:57
  • Exactly - for function parameters the array is accepted as a pointer. `sizeof(array)` only works when the array dimension is known in that part of the program. Consider that `sizeof` is always evaluated at compile time, and it's entirely possible for a function `f(int a[])` to be called twice with different sized arrays, so it's an impossible situation. (In C++ you can use templates: `template void f(int (*)[N]) { /* now N holds the array size */ }`.) – Tony Delroy Apr 19 '13 at 10:02
0

If you pass an array to a function and don't provide the length, you can't find it, because the array decays to as pointer whose size is always 32 (64) bit.

bash.d
  • 13,029
  • 3
  • 29
  • 42