c - 通过引用传递失败 [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");
}
解决方案
您传递给函数的内容与预期的不符。
to 的最后两个参数targetSum
是 type int
,但您传入的 value 是 type int *
。你的编译器应该已经警告你了。
将函数参数更改为指针:
int targetSum(int arr[], int size, int target, int *index1, int *index2)
然后在函数体中根据需要取消引用它们。
推荐阅读
- node.js - Docker - 某些软件包无法安装。这可能意味着您请求了一个不可能的情况
- java - Landroid/media/MediaExtractor 类中没有虚拟方法 getSampleSize()J
- docker - 如何创建一个 dockerfile 以根据作为数组列表的参数从本地复制文件?
- java - 将android java webview项目转换为kotlin
- operating-system - 由于 FAT 表中的多步遍历导致高寻道时间
- javascript - 有没有办法在打字稿中获取函数参数的名称?
- dataset - 如何从 h5 文件中提取图像和字幕数据集?
- c# - C# 异步控制台输入行为
- javascript - 样式化组件不会覆盖内联样式
- python - 在 SQLAlchemy 中实现 Python 的 `all()` 函数