简体   繁体   English

C++:通过 function 传递指针数组的语法

[英]C++: Syntax of passing a pointer array through a function

So I have these 2 methods: the first is meant to take in 5 integer values, sum them up, then call the findLowest() method that returns the lowest found value, and subtracts that from the sum (then divides by 4 and prints results to screen).所以我有这两种方法:第一种是获取 5 个 integer 值,将它们相加,然后调用返回最低找到值的 findLowest() 方法,并从总和中减去该值(然后除以 4 并打印结果向屏幕)。

I think the issue I'm having is the values it's returning are memory addresses.我认为我遇到的问题是它返回的值是 memory 地址。 I've tried to understand how to dereference integers to get the value, but truth be told all of the online resources I've looked up have gone over my head.我试图了解如何取消引用整数以获得值,但说实话,我查找过的所有在线资源都让我头疼。

Below is what I have so far:以下是我到目前为止所拥有的:

void calcAverage(int* arr[5])
{
   int sum = 0;

   for (int a = 0; a < 5; a++)
      sum += *arr[a];

   sum -= findLowest(*arr);

   cout << "AVERAGE " << (sum / 4) << endl;
}


int findLowest(int* arr[5])
{
   int lowest = *arr[0];

   for (int a = 1; a < 5; a++)
   {
      if ((int)arr[a] < lowest)
         lowest = *arr[a];
   }


   return lowest;
}

On top of that, on the line that says最重要的是,在上面写着

sum -=findLowest(*arr); sum -=findLowest(*arr);

it pops up an error that reads它弹出一个错误,上面写着

argument of type "int *" is incompatible with parameter of type "int **" “int *”类型的参数与“int **”类型的参数不兼容

Thanks for the help in advance, and sorry if the post's a bit scattershot: I'm not really confident with this pointer/reference stuff to begin with.提前感谢您的帮助,如果帖子有点散漫,我深表歉意:我对这个指针/参考资料一开始并没有真正的信心。

You are almost there, but you should not dereference on this line:你快到了,但你不应该取消对这一行的引用:

sum -= findLowest(*arr);

Instead, just pass in the array, because that is what the function expects:相反,只需传入数组,因为这是 function 所期望的:

sum -= findLowest(arr);

Unrelated:无关:

If you can, use a std::vector or std::array , the former for dynamically sized arrays, the latter for a compile time array.如果可以,请使用std::vectorstd::array ,前者用于动态大小的 arrays,后者用于编译时数组。 These both are safer, have more functions, and are easier to pass around.这两种都更安全,功能更多,也更容易传递。

Also use smart pointers for ownership of pointers instead of raw pointers.还使用智能指针代替原始指针来拥有指针。 Smart pointers manage the ownership of an object so that you do not need to manually call new and delete .智能指针管理 object 的所有权,因此您无需手动调用newdelete

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM