Click here to Skip to main content
15,896,207 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
C++
#include<iostream>
using namespace std;
class peak
{
    int n,*p,*q;
public:
    void get()
    {
        cout<<"\nenter how many elements u want in array";
        cin>>n;
    }
    void create()
    {
        p=new int[n];
        q=new int[n];
    }
    void find();
    void show();
    void input();
    void del()
    {
        delete []p;
        delete []q;
    }
};
void peak:: find()
    {
        int j=0,i=1;
        if(p[0]>p[1])
            q[j++]=p[0];
        for(i=1;i<n-1;i++)
        {
            if(p[i]>p[i-1] && p[i]>p[i+1])
                q[j++]=p[i];
        }
        if(p[i]>p[i-1])
            q[j]=p[i];
    }
    void peak::show()
    {
        cout<<"\nthe peak elements are:";
        for(int i=0;i<n;i++)
            //showing different garbage for *(q+i):6750404 and q[i]:3080388
            cout<<q[i]<<"\t";
    }
    void peak::input()
    {
        cout<<"\nenter elements ";
        for(int i=0;i<n;i++)
            cin>>p[i];
    }
    int main()
    {
        peak p;
        p.get();
        p.create();
        p.input();
        p.find();
        p.show();
        p.del();
        return 0;
    }


What I have tried:

the expression:
p=new int[n](0) doesn't works as is during dynamic allocation of single integer as:p=new int(25);
also,output of above program for n=4 and entries:5 10 20 15 is:
20 garbage 0 0
required output:20 0 0 0
for the same code,if n=7 with entries:10 20 15 2 23 90 67 is:
20 90 0 0 0 0 0 which is the required output without any garbage!
why so?kindly help.
Posted
Updated 9-Aug-17 6:43am
v2

1 solution

Quote:
How to initialise dynamic integer array with 0 when using new pointer in C++
See here: initialization - How to initialise memory with new operator in C++? - Stack Overflow[^].

On my linux box, your program produces the expected results.
 
Share this answer
 
Comments
Member 13057504 10-Aug-17 0:41am    
ptr=new int[n]() works for default initialization of dynamic array with 0.But,if i want to initialize the array with some other number/char(in case of string) is there a way else than initializing with loop?the initialization syntax :ptr=new int[n](25) is not valid and shows error!
CPallini 10-Aug-17 2:38am    
As far as I know, you have to iterate.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900