0

所以,我只是在处理 C 代码,特别是一个接受 3 个参数的函数:一个数组、数组的大小以及您想要返回的最大元素的数量。

这是我的代码:

int* findMaxElements(int base_array[],int size_of_base_array, int number_of_elements_to_find);

int main( void )
{

    printf("Find Max Values in an Array\n\n");

    // Set up array

    int kinch[6] = {1,2,3,4,5,6};

    // Pass to function and get a pointer to new array filled with only the max elements

    int *given = findMaxElements(kinch,6,3);

    for(int i = 0; i < 3; i++)
    {
        printf("\nMax Value = %d\n", *(given + i));
    }
    return 0;

}

int* findMaxElements(int base_array[],int size_of_base_array, int number_of_elements_to_find)
{

    // Set up all initial variables

    int i,k,c,position;
    int maximum = 0;



    int returnArray[100];

    /*Actual Algorythm */

    for(i = 0; i < number_of_elements_to_find; i++)
    {

        // Get the max value in the base array

        for(k = 0; k < size_of_base_array; k++)
        {
            if(base_array[k] > maximum)
            {
                maximum = base_array[k];
            }
        }

        // Find the position of the max value

        for(position = 0; position < size_of_base_array; position++)
        {

            if(base_array[position] == maximum)
            {
                break;
            }

        }

        // Delete the maximum value from the array and shift everything

        for(c = position - 1; c < size_of_base_array - 1; c++)
        {
            base_array[c] = base_array[c+1];
        }

        // Reduce the size of the array

        size_of_base_array -= 1;

        // Push max value into return array

        returnArray[i] = maximum;

        // Reset max value

        maximum = 0;
    }

    return returnArray;

}

我感觉函数的某个地方出了点问题。

// Set up array

    int kinch[6] = {1,2,3,4,5,6};

    // Pass to function and get a pointer to new array filled with only the max elements

    int *given = findMaxElements(kinch,6,3);

    for(int i = 0; i < 3; i++)
    {
        printf("\nMax Value = %d\n", *(given + i));
    }

这应该输出数字 6、5 和 4,因为它们是数组中最大的三个,但是我得到的输出始终是 6、6 和 6。它有什么问题?

4

3 回答 3

2

这可能不是您唯一的问题,但在线路中

for(c = position - 1; c < size_of_base_array - 1; c++)
    {
        base_array[c] = base_array[c+1];
    }

您将元素[c+1](最大值)复制到[c]- 所以您不断找到最大值......

您应该从 开始循环c = position,而不是c = position - 1

并在用于存储返回值的数组前面添加关键字static,以便它们保持有效(这是解决 Jonathan Leffler 发现的问题的一种方法)。

于 2013-04-14T21:39:32.193 回答
2

一个问题是您returnArray在函数中返回一个指向局部变量 的指针。你不能可靠地做到这一点——它会导致未定义的行为。

很可能还有其他问题,但这足以成为一个展示者。

于 2013-04-14T21:38:18.517 回答
1

寻找第 K 个最大元素的整个方法既不高效也不优雅。我会建议你修改你的算法,虽然上面的建议可以正常工作,但这不是解决这个问题的好方法。

我建议您查看以下链接以修改您的算法 http://www.geeksforgeeks.org/k-largestor-smallest-elements-in-an-array/

于 2013-04-14T21:48:23.220 回答