使用指针创建函数
Creating functions using pointers
我创建了一个函数,它接受2个参数(数组的名称、数组的大小),我所做的是接受数组的最大元素减去最小元素。但我现在想做的是使用指针创建相同的函数,但由于某种原因,我总是得到0的结果。这是代码:
#include <iostream>
#include <stdlib.h>
#include <cmath>
using namespace std;
const void pntArray(int arrName[], unsigned sizeOfArray);//The first function which takes the size of the array and the array name and prints the sub of the max-min
void pntTheArray(int *(arrName), unsigned sizeOfArray);//Version of the first function, using pointers
int main()
{
int someArr[3]={7,2,6};
int pointerArray[5]={7,6,5,4,10};
pntArray(someArr, 3);//Example of the function without the pointers
pntTheArray(someArr, 3);//Example of the function with the pointers
}
void pntTheArray(int *arrName, unsigned sizeOfArray){
int max = 0;
int min = 999999;
for (int x = 0;x<sizeOfArray;x++){
if (*arrName+x>max){
max = *arrName;
}
if(*arrName+x<min){
min = *arrName;
}
}
cout<<"The maximum element minus the the minimum element is: "<<(unsigned)(max-min)<<endl;
}
const void pntArray(int arrName[], unsigned sizeOfArray){
int max=0;
int min = 999999;
for (int x = 0;x<sizeOfArray;x++){
if(arrName[x]>max){
max = arrName[x];
}
if (arrName[x]<min){
min = arrName[x];
}
}cout<<"The maximum element minus the the minimum element is: "<<(unsigned)(max-min)<<endl;}
基本上,我想制作第一个数组的一个版本。那么,为了得到第二个函数的结果只有0,我犯的错误在哪里呢?
您在if
语句中使用的表达式:
*arrName+x>max
相当于:
arrName[0]+x > max
这不是你需要的。您需要使用:
*(arrName+x) > max
或
arrName[x] > max
您需要再更改几行出现相同错误的行。
更改:
if (*arrName+x>max){
max = *arrName;
}
if(*arrName+x<min){
min = *arrName;
}
至
if (*(arrName+x) > max){
max = *(arrName+x);
}
if(*(arrName+x) < min){
min = *(arrName+x);
}
这并不像你想象的那样:
if (*arrName+x>max) {
*
(去引用操作)具有比+
操作更高的优先级。请参见运算符优先级。所以你真正要做的是:
if ( (*arrName) + x > max) {
您应该使用:
if (*(arrName + x) > max) {
或
if (arrName[x] > max) {
你得到零的原因是因为你在几个地方都这样做了。试试这个:
void pntTheArray(int *arrName, unsigned sizeOfArray){
int max = 0, min = 999999;
for (int x = 0;x<sizeOfArray;x++){
cout << "i: " << x << " val: " << *(arrName+x) << "n";
if (*(arrName+x)>max){
max = *(arrName+x); // Note you weren't setting this correctly either!!!
}
if(*(arrName+x)<min){
min = *(arrName+x); // Note you weren't setting this correctly either!!!
}
}
cout<<"The maximum element minus the the minimum element is: "<<(unsigned)(max-min)<<endl;
}
实例
取消引用arrName
时缺少括号
代替
*arrName + x>max
你应该
*(arrName + x)>max
相关文章:
- 通过构造函数创建的所有对象都具有相同的向量
- 通过构造函数创建一些值并尝试添加到文档中使用 rapidjson 不起作用
- 为 NewObjectA() 函数创建 jvalues 的参数数组时出错 - JNI Invocation API
- 使用带有 ref 参数的成员函数创建线程时出现编译错误
- C++ :: 如何捕获由 void 函数创建的矩阵
- 通过零参数构造函数创建的 glm::mat4 应该包含哪些值?
- 用于基于成员字段或函数创建比较器的快捷方式
- std::使用类成员函数创建线程 - 最佳实践
- 为C++重载函数创建SWIG类型映射
- 使用成员函数创建std::函数不会编译
- 如何为返回特定类型的函数创建 SWIG 类型图
- 为具有多个参数的函数创建 SWIG 类型图的更简单方法?
- 通过另一个宏创建的函数创建所有列表的宏
- std::map<int, A> 运算符 [] 需要使用空构造函数创建 A
- 无法使用 CreateWindowEx 函数创建窗口
- c++ 从成员函数创建新线程并移动对象和整个对象
- 无法使用 c++ 中的类成员函数创建/写入文件
- 使用makeword函数创建错误e0109-表观呼叫的括号前表达式必须具有(指针到 - )函数类型
- 为 OpenMP 函数创建别名 ||部分禁用 openMP
- 稍后使用<Class>调用类构造函数创建 std::vector