首页 > 解决方案 > 通过引用传递失败 [C 编程]

问题描述

我正在尝试使用函数 targetSum 来确定数组中是否有两个值与用户输入的目标值匹配。它接受数组、目标、2 个索引和数组的大小。当我尝试在主函数中输出结果时,索引的值不会改变(即使我作为参考传递)。帮助表示赞赏![下面的代码]

int targetSum(int arr[], int size, int target, int index1, int index2)
{
    int max, min, sum;

    index1 = 0;
    index2 = size - 1;

    min = arr[index1];
    max = arr[index2];

    while (index1 != index2) {

        sum = max + min;

        if (sum == target) {
            return 1;
        }
        else if (sum < target) {
                index1++;
                min = arr[index1];
        }
        else if (sum > target) {
                index2--;
                max = arr[index2];
            }
        }
    return -1;
}

int index1, index2 = 0;
int target;
        if(target == -999){ // the program exits if the user enters target as -999
            printf("Good Bye");
            break;
        }

        if (targetSum(toArr, size, target, &index1, &index2) == 1) {
            printf("Output: Success! Elements at indices ");
            printf("%d", index1);
            printf(" and ");
            printf("%d", index2);
            printf(" add up to ");
            printf("%d", target);
            printf("\n");
        }
        else {
            printf("Output: Target sum failed!\n");
        }

标签: c

解决方案


您传递给函数的内容与预期的不符。

to 的最后两个参数targetSum是 type int,但您传入的 value 是 type int *。你的编译器应该已经警告你了。

将函数参数更改为指针:

int targetSum(int arr[], int size, int target, int *index1, int *index2)

然后在函数体中根据需要取消引用它们。


推荐阅读