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;
std::arrayorstd::vectorand pass by reference, as they know their size (or pass their begin and end iterators)std::findfunctionintsinceNULLis a pointer value. This is the perennial problem with sentinel values, there is nothing you can put into anintthat can't be interpreted as representing a validint. 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.NULLonly works for pointers because C demands that0can never be a valid address.