1

How can I get arrayLength from user defined function?

int getArrayLength(int *arr){
   //our logic
   return result;
}
Mr_Pouet
  • 4,061
  • 8
  • 36
  • 47
user3110007
  • 75
  • 1
  • 2
  • 4
  • One way you could deterimine the length is to set the last element to a delimiter value like 0, or pass in the size along with arr. The first method is unrecommended though. – sudowoodo Feb 03 '14 at 17:23
  • This might be the time to consider switching to a higher level language – David Heffernan Feb 03 '14 at 17:26
  • 1
    down voting simply because a question is a duplicate is overkill, especially when 1) the OP is new to SO. 2) the question is clearly and succinctly asked. – ryyker Feb 03 '14 at 17:27

3 Answers3

3

Simply: you cannot. You should pass it as another argument:

int getArrayLength(int *arr, int size){ ...

If you try with sizeof, it will return the size of the pointer. You can also use a special value to indicate the last element of your array (like 0 for strings), but adding a convention can make things more complicated.

fede1024
  • 3,099
  • 18
  • 23
3

You'll need to do one of two things:

  1. Have the caller provide the length, or...

  2. Agree on a sentinel value that lets you detect the end of the array.

In the general case, the right answer is option 1. You shouldn't write functions that take C arrays without also taking a length parameter.

In some specific cases, option 2 works pretty well. For example, \0 is used to mark the end of strings, which are just character arrays. If 0 isn't a valid value for the elements of array, that could work for cases other than strings. But generally, go with option 1.

Caleb
  • 124,013
  • 19
  • 183
  • 272
  • 2
    Presented concepts _similar_ to, but improved over other answers, and well stated, with good supporting reasons. Like that you validated use of sentinel values. +1 – ryyker Feb 03 '14 at 17:31
2

Pass array length to the function too otherwise you can't. This is because sizeof(arr) will give you size of the pointer to int, not the size of entire array.

haccks
  • 104,019
  • 25
  • 176
  • 264