使用指针创建函数

Creating functions using pointers

本文关键字:函数 创建 指针      更新时间:2023-10-16

我创建了一个函数,它接受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