gpt4 book ai didi

c - 我在数组中的指针无法按预期工作

转载 作者:行者123 更新时间:2023-11-30 14:36:59 25 4
gpt4 key购买 nike

我想创建一个函数,它接受 1:array_of_int 和 2:size_of_array,然后返回 3 个最大 int 的总和。代码如下:

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

int max_3(int arr[], int asize)
{
int max_arr[3];
int max =0;
int sum = 0;
int* pi;

for(int j=0; j<3; j++)
{
for(int i =0; i<asize;i++)
{
if(arr[i] > max)
{
max = arr[i];
pi = (arr + i); // to know the address of the max int of 'i' cycle
}
}
max_arr[j] = max;
*pi = 0; // make the max int = 0 so that the next 'i' cycle doesnt have the previous max in it
//(so it can look for another max value - the second one)
}

for(int i=0; i<3; i++)
sum += max_arr[i];

return sum;
}


int main (int argc, char** argv) {
int arr[6] = {1,5,9,12,16,14};
printf("%i\n",max_3(arr, 6));
return (EXIT_SUCCESS);
}

指针pi不会使当前max值为0,下一次循环for (int i..) 与上一个一样再次制作最大的一个。因此,它不是返回 max val1 + val2 + val3,而是返回 3 * val1(最大的一个)——在我的特定示例中——它打印出 48 而不是 42 ( 12 + 16 + 14) - 理应如此。但是当我将地址(我的指针指向的)值设置为 0 时该怎么办?我不太明白这一点。

最佳答案

您的if语句:

if (arr[i] > max)

在您第一次找到 max 后(j > 0 时),将不再输入。

您需要在以下时间后将其归零:

max_arr[j] = max;
max = 0;

关于c - 我在数组中的指针无法按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57677976/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com