使用指针创建函数

时间:2015-11-03 18:33:35

标签: c++ arrays function

我创建了一个函数,它接受2个参数(数组的名称,数组的大小),我所做的是将数组的max元素减去最小值。 但我现在要做的是使用指针创建相同的函数,但我总是得到一个由于某种原因为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的错误呢?

3 个答案:

答案 0 :(得分:2)

这不符合你的想法:

 if (*arrName+x>max) {

*(deereference操作)的优先级高于+操作。 See operator precedence.所以你真正在做的是:

 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;
}

Live example

答案 1 :(得分:2)

您在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);
}

答案 2 :(得分:0)

取消引用arrName

时,您缺少括号

而不是

*arrName + x>max

你应该

*(arrName + x)>max