I created a program that will use a dynamic array by using pointer to find the max and min from a set for integer that the user will enter.
I actually can get the output of max, but not for min; I found out my dynamic array will result to 0 after the calculation from the function of max, and made my min became the value of the assigned value of min.
I have no idea why it is like this – I tried many ways, but these were useless so can someone explain why, and provide a solution if possible or give me some hint for how to get through the solution?
Thank your replies
seem like my code had confused to your
Sorry
the program intent to get the maximum and minimum digits from an amount of integers
From I what I tried to say is after calculation from the function of max, the data from the dynamic array would become 0, and when program go through the function of min, it would not gonna run because the data from dynamic array had been set to 0
So actually what I wanna ask is is there anyway to make the data from the dynamic array not become to 0 after the function of max?
Sorry for my poor English
#include <iostream>
using namespace std;
void max(int*, int);
void min(int*, int);
int main()
{
int *ptr;
int i;
int size;
cout << "how many integer: ";
cin >> size;
ptr = new int[size];
for (i = 0; i < size; i++)
{
cout << "integer#" << i << ": ";
cin >> *ptr + i;
}
max(ptr, size);
min(ptr, size);
delete [] ptr;
return;
}
void max(int* ptr, int size)
{
int i;
int j;
int max = 0;
for (i = 0; i < size; i++)
{
while (*ptr + i != 0)
{
j = *ptr + i % 10;
if (j > max)
{
max = j;
}
*ptr + i /= 10;
}
}
cout << max << endl;
}
void min(int* ptr, int size)
{
int i;
int j;
int min= 0;
for (i = 0; i < size; i++)
{
while (*ptr + i != 0)
{
j = *ptr + i % 10;
if (j < min)
{
min= j;
}
*ptr + i /= 10;
}
}
cout << min<< endl;
}
I do not know what compiler you have used, but your code is not even compiling without some modifications on my GCC 4.6.
*ptr + ibecomes*(ptr + i).return;at the end ofmain()becomesreturn 0;.The other issue is that in function
void min(int* ptr, int size), you are initializingminas0. What you should really do isint min = std::numeric_limits<int>::max();so thatminhas the highest possible integer value. Don’t forget the#include <limits>.Here is a code that finds the minimum digit and maximum digit without modifying the original array (a good practice),