Error in execution

I have the following code to find first and second largest elements of an array:

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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
using namespace std;
#include<iostream>
#include<conio.h>
#include<cstdio>
#include<string.h>

int* create(int);
int maximum(int *,int);
int second_max(int *,int);
void freememory(int*);

int main(void)
{
    int *p,size;
    cout<<"Enter size of the array:";
    cin>>size;
    p=create(size);
    cout<<"\nMaximum elemnt in the array is:"<<maximum(p,size);
    cout<<"\nSecond maximum element in the array is:"<<second_max(p,size);
    freememory(p);
    cin.get();
    return 0;
    
}

int* create(int s)
{
     int *a;
     a=new int[s];
     cout<<"Enter elements of array:";
     for(int i=0;i<s;i++)
     {
             cin>>*(a+i);
             cout<<"\n";
     }
     return a;
}

int maximum(int *a,int s)
{
    cout<<"\nFinding maximum element in array:";
    int max;
    max=a[0];
    for(int i=0;i<s;i++)
    {
       if(*(a+i)>max)
       max= *(a+i);
    }
    return max;
}

int second_max(int *a,int s)
{
    cout<<"\nFinding second maximum element in array:";
    int max,smax;
    max=a[0];
    for(int i=0;i<s;i++)
    {
       if(*(a+i)>max)
       max= *(a+i);
    }
    smax=a[0];
    for(int i=0;i<s;i++)
    {
      if((*(a+i)>=smax) && (*(a+i)!=max))
      smax=*(a+i);
    }
    return smax;
}

void freememory(int *a)
{
     cout<<"\nFreeing memory now:";
     delete(a);
}


The above code compiles fine but when executing does not produce the desired output.. Please help,,I am using dev c++ as compiler..
What is the desired output?

What output are you getting?

EDIT: Unrelated to your problem, but you're freeing your memory incorrectly. Things allocatd with new[] must be deleted with delete[].

line 74 should look like this: delete[] a;
Last edited on
Thanks for your answer.. I corrected it now.. But I need answer that why is the code not producing the desired output..
Well, when I run the code, everything goes fine and I can create the array..

But the statement : "\nMaximum element in the array is:"<<maximum(p,size);
is not being printed means there is some problem with the maximum function which I am unable to find out.
I got the mistake.. getch() was missing..
Topic archived. No new replies allowed.