10

I want to retrieve the index in the array where the value is stored. I know the value of the item at that point in the array. I'm thinking it's similar to the findIndex function in c#. For example, array[2] = {4, 7, 8}. I know the value is 7, how do I get the value of the index, 1, if I know it is at array[1]?

5
  • 2
    Write a loop from 0 to the size of the array, compare current element to the given value, stop when found. Commented Jul 28, 2014 at 20:43
  • 1
    If you know the array is sorted, you can also use binary search Commented Jul 28, 2014 at 20:47
  • @user1798299 May I append my post to show how to use bsearch?:) Commented Jul 28, 2014 at 21:11
  • @VladfromMoscow - just do it. Commented Jul 28, 2014 at 21:18
  • @VladfromMoscow of course! Commented Jul 28, 2014 at 21:22

3 Answers 3

12

For example you can define the corresponding function the following way

size_t FindIndex( const int a[], size_t size, int value )
{
    size_t index = 0;

    while ( index < size && a[index] != value ) ++index;

    return ( index == size ? -1 : index );
}

Also instead of type size_t you can use type int.

But the better way is to use standard algorithm std::find or std::find_if declared in header <algorithm> provided that you use C++

For example

#include <algorithm>
#include <iterator>

int main()
{
    int a[] = { 4, 7, 8 };

    auto it = std::find( std::begin( a ), std::end( a ), 7 );

    if ( it != std::end( a ) )
    {
        std::cout << "The index of the element with value 7 is " 
                  << std::distance( std::begin( a ), it )
                  << std::endl;
    }
} 

The output is

The index of the element with value 7 is 1

Otherwise you have to write the function yourself as I showed abve.:)

If the array is sorted you can use standard C function bsearch declared in header <stdlib.h>

For example

#include <stdio.h>
#include <stdlib.h>


int cmp( const void *lhs, const void *rhs )
{
    if ( *( const int * )lhs < *( const int * )rhs ) return -1;
    else if ( *( const int * )rhs < *( const int * )lhs ) return 1;
    else return 0;
}

int main() 
{
    int a[] = { 4, 7, 8 };

    int x = 7;
    int *p  = ( int * )bsearch( &x, a, 3, sizeof( int ), cmp );

    if ( p != NULL ) printf( "%d\n", p - a );

    return 0;
}
Sign up to request clarification or add additional context in comments.

13 Comments

In your first example, you have return type of size_t. This is typedef unsigned int size_t;, so returning a -1 may be problematic. Your second example looks like C++. (tagged C)
OP is tagged C, not C++ though. Other than that I like both approaches, except size_t cannot be negative.
@ryyker IIRC -1 is implicitly converted to size_t, which is the same as SIZE_MAX (since overflow/underflow for unsigned integers is not UB)
@VladfromMoscow given that the question is tagged as C, then while a C++ answer is demonstrative, it cannot be used as C code.
@VladfromMoscow true, but it's irrelevant to this particular question.
|
2

First its important that the argument list contain size information for the array, i.e. passing a pointer to an array only does not provide enough information to know how many elements the array has. The argument decays into a pointer type with no size information to the function.

So given that, you could do something like this:

int findIndex(int *array, size_t size, int target) 
{
    int i=0;
    while((i<size) && (array[i] != target)) i++;

    return (i<size) ? (i) : (-1);
}

For small arrays this approach will be fine. For very large arrays, some sorting and a binary search would improve performance

Comments

1

Here's my version without a additional variable.

// Return index of element starting
// Return -1 if element is not present
int indexOf(const int elm, const int *ar, int ar_cnt)
{
    // decreasing array count till it reaches negative
    // arr_cnt - 1 to 0
    while (ar_cnt--)
    {
        // Return array index if current element equals provided element
        if (ar[ar_cnt] == elm)
            return ar_cnt;
    }

    // Element not present
    return -1; // Should never reaches this point
}

Hope the comments are self explanatory!

Comments

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.