Stack problem

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
#include <iostream>
using namespace std;
class stack{
private:
	int *st;
	int s;
	int top;
public:
	stack(int);
	void set_values();
	void get_values();
	void push(int);
};

stack::stack(int x)
{
	s=x;
	top=0;
	st=new int[s];
}

void stack::set_values()
{
	for(int i=0; i<s; ++i)
		st[i]=rand()%10;
}
void stack::get_values()
{
	for(int i=0; i<s; ++i)
		cout<<st[i]<<endl;
}

void stack::push(int x)
{
	st[++top]=x;
}


int main()
{
	stack sc(10);
	
	sc.set_values();
	sc.get_values();
	sc.push(?);

	system ("Pause");
	return 0;
}


sc.push(?);

What should I put here as argument?
Last edited on
fist of all srand was not declared, and what do you expect the main to do there, cause clearly it does nothing
include the cstdlib header and call the functions in your main.then everything would be fine
Whats wrong here?
That depends on what do you expect.

Currently the only problem I see is a memory leak.
Are you sure.Even though everything is done in the main.I used valgrind and it shows no memory leak.although he should implement a destructor , but why is the memory deallocated Coder777
even used gdb....still no leaks
The problem is, its doesnt display the desired outputs. In fact doesnt display anything.
I need the random values..
Try this

#include <iostream>
#include <cstdlib>
using namespace std;
class stack{
private:
int *st;
int s;
int top;
public:
stack(int);
~stack();
void set_values();
void get_values();
};

stack::stack(int x)
{
s=x;
top=0;
st=new int[s];
}
stack :: ~stack()
{
delete [] st;
}
void stack::set_values()
{
for(int i=0; i<s; ++i)
st[i]=rand()%10;
}
void stack::get_values()
{
for(int i=0; i<s; ++i)
cout<<st[i]<<endl;
}


int main()
{
stack sc(10);

sc.set_values();
sc.get_values();
return 0;
}
But the randomm numbers will always be the same.If thats the case then fine.If not consider srand and time functions
~stack();

Whats this? Can you explain it simply?
its a destructor.to deallocate memory from the heap that you allocated.
Ya I can use srand; bt thats not a big problem, dude.
The problem is, the output is with garbage values..
Oh ya I got the random values. Thanks a lot. But whats about this:
~stack();

and this:
stack :: ~stack()
{
delete [] st;
}
Got it. Thanks..
Topic archived. No new replies allowed.