1

So I'm trying to figure out a way to iterate though an array passed into a function without knowing the size. I run into infinite loops with my code because the arrays are not NULL terminated. Since the array is turned into a pointer through the function, I cannot use sizeof(Array)/sizeof(int) to get the number of elements. Is there any way of doing this without NULL terminating my arrays?

My find function:

int find(const int* arr, int val)
{
    int pos = 0;
    while (arr != NULL)
    {
        if (*arr == val)
        {
            return pos;
        }
        pos++;
    }
    return -1;
};

My main:

int IntArr[] = { 1, 2, 3, 4, 5 };
int index = find(IntArr, 4);
cout << "find(IntArr, 4)" << endl;
cout << "index: " << index << endl << endl;
4
  • 1
    If you don't know the size, you are SOL. If you guess, you will guess wrong. You say there's no terminator? Ok, then you have to pass the lenghth some other way, like in an additional argument. Commented Sep 28, 2014 at 18:33
  • 1
    Pass the size of the array, or use std::array or std::vector and pass by reference, as they know their size (or pass their begin and end iterators) Commented Sep 28, 2014 at 18:35
  • PS there is std::find function Commented Sep 28, 2014 at 18:39
  • You can never "NULL terminate" an array of int since NULL is a pointer value. This is the perennial problem with sentinel values, there is nothing you can put into an int that can't be interpreted as representing a valid int. If your array was only supposed to contain positive integers, then you could use a sentinel such as -1, but if it could contain any integer at all then no sentinel value is appropriate. NULL only works for pointers because C demands that 0 can never be a valid address. Commented Sep 28, 2014 at 18:44

1 Answer 1

1

For example you could define a template function that accepts an array by reference

template <size_t N>

int find( const int ( & arr )[N], int value )
{
    int pos = 0;

    while ( pos < N && arr[pos] != value ) ++pos;

    return pos == N ? -1 : pos;
}

Take into account that there is standard algorithm std::find declared in header <algorithm>. You could write for example

#include <algorithm>
#include <iterator>

//..

int IntArr[] = { 1, 2, 3, 4, 5 };
auto ptr = std::find( std::begin( IntArr ), std::end( IntArr ), 4 );
cout << "find( std::begin( IntArr ), std::end( IntArr ), 4)" << endl;
cout << "index: " << std::distance( std::begin( IntArr ), ptr ) << endl << endl;
Sign up to request clarification or add additional context in comments.

1 Comment

Or just use std::find and pass two iterators.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.