To find max and minmum values from pointer

hey i just did a small work to find max and min number from an array
how can i change the function call to call the pointer and not the array
like int *p;
p=array[n]
max(*p)?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
  #include<iostream>
using namespace std;
void max(int array[]);
void min(int array[]);
int main(){
int array[4];
for(int i=0; i<4;i++){
cout<<"Enter Numbers: "<<endl;
cin>>array[i];
}
max(array);
min(array);

}
void max(int array[]){
    int max=array[0];
    for(int j=0;j<4;j++){
        if(array[j]>max)
            max=array[j];

    }
    cout<<"The max number is; "<<max<<endl;

}
void min(int array[]){
    int min=array[0];
    for(int k=0;k<4;k++){
        if(array[k]<array[0])
            min=array[k];
    }
    cout<<"The minmum number is: "<<min<<endl;
}
another quastion if you might help
why when i do like this
int array[4];
int n=sizeof(array)
cout<<n;

its print 16 and not 4?
how can i change the function call to call the pointer and not the array

Well, it should be obvious that you'll need to pass the pointer as an int*:

void max(int* array)

If you were writing this as a reusable library function, I'd say you also need to pass the size of the array, i.e. the number of elements in the array, as the function would have no way of knowing how many elements are in the array. However, it seems you've already writing the function to assume that the size of the array is 4, so you can keep that assumption if it's valid.

I would say that you should use a single constant for the size of the array, rather than using a magic number everywhere, so:

1
2
3
4
5
6
7
const size_t SIZE = 4;
int array[SIZE];

//...

    for(int j=0;j<SIZE;j++){
    // ... 


That makes it easier to see what that number actually means whenever it crops up in the code, and makes it easier to change if you ever want to.

why when i do like this
int array[4];
int n=sizeof(array)
cout<<n;

its print 16 and not 4?


sizeof() gives the size of the object in bytes.
Last edited on
thank you so much mikeboy!!
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
 #include<iostream>
using namespace std;
void max(int* array);
void min(int* array);
const size_t SIZE = 4;
int array[SIZE];
int main(){
for(int i=0; i<SIZE;i++){
cout<<"Enter Numbers: "<<endl;
cin>>array[i];
}
max(array);
min(array);

}
void max(int* array){
    int max=array[0];
    for(int j=0;j<SIZE;j++){
        if(array[j]>max)
            max=array[j];

    }
    cout<<"The max number is; "<<max<<endl;

}
void min(int *array){
    int min=array[0];
    for(int k=0;k<SIZE;k++){
        if(array[k]<array[0])
            min=array[k];
    }
    cout<<"The minmum number is: "<<min<<endl;
}


its working great .

Cool! You're welcome. Glad it worked :)
Last edited on
Topic archived. No new replies allowed.