如何获取数组的索引号而不是元素?

How do you get the index number of an array rather than the element?

我已经编写了一个基本程序来查找数组中的最大数并打印它:

#include <stdio.h>

int main(void)
{
    int numbers[] = {3, 5, 12, 1, 4};
    int largest;

    largest = numbers[0];

    for (int i = 0; i < sizeof(numbers) / sizeof(numbers[0]); i++)
    {
        if (largest < numbers[i])
        {
            largest = numbers[i];
        }
    }

    printf("The largest number in the array is %i\n", largest);
}

我需要做什么才能打印 The largest number in the array is numbers[2]?

而不是打印 The largest number in the array is 12

不使用值,而是使用索引:

#include <stdio.h>

int main(void)
{
    int numbers[] = { 3, 5, 12, 1, 4 };
    int largest;

    largest = 0;

    for (int i = 1; i < sizeof(numbers) / sizeof(numbers[0]); i++)
    {
        if (numbers[largest] < numbers[i])
        {
            largest = i;
        }
    }

    printf("The largest number in the array is numbers[%d]\n", largest);
    return 0;
}

一种方法是跟踪索引

#include <stdio.h>

int main(void)
{
    int numbers[] = {3, 5, 12, 1, 4};
    int largest;
    int index = 0;

    largest = numbers[0];

    for (int i = 0; i < sizeof(numbers) / sizeof(numbers[0]); i++)
    {
        if (largest < numbers[i])
        {
            largest = numbers[i];
            index   = i;
        }
    }

    printf("The largest number in the array is %d at numbers[%d]\n", largest,index);
    return 0;
}

我会做类似的事情:

#include <stdio.h>

int
main(void)
{
        int numbers[] = {3, 5, 12, 1, 4};
        int *largest = numbers;
        int *end = numbers + sizeof numbers / sizeof *numbers;

        for(int *s = numbers; s < end; s++ ){
                if( *s > *largest) {
                        largest = s;
                }
        }
        printf("The largest number in the array is %d, at position %td\n",
                 *largest, largest - numbers);
}