Hello people,
I need help with a template program that i am writing .
I am trying to emulate Stack operations using template class which works fine with all the datatypes except char* when using all the datatypes at the same time.
What I am trying to do is pass an array of character strngs (char*) to the push().
I know that memory allocation is needed to store the strings on the stack which i find difficult to write because then I'll have to write the allocation code in the push function which I dont think is correct since the same function is used by other datatypes.
I dont get any error messages but am not able to get the proper output because the strings are not stored on the stack
However I am perfectly able to run the program when I am using just the char* datatype without any other datatypes (that's obvious). The program also works fine when I am using the string datatype.
My only objective is to use the char* with others at the same time.
So how can I do that or is it not possible?
Here's my code:
#include<iostream>
using namespace std;
template<class T> class Stack{
public:
Stack() : top(0){}
void push(T ele);
T pop();
private:
int top;
T array[10] ;
};
template<class T>T Stack<T>::pop(){
assert(top > 0);
return (array[--top]);
}
template<class T>void Stack<T>::push(T ele){
assert(top < 10);
array[top++] = ele;
}
int main(){
Stack<int> Si;
Si.push(2);
Si.push(3);
Stack<pop> Sf;
Sf.push(2);
Sf.push(3);
Stack<char*> Scptr;
char ar[] = "abhi";
char* ar2 = new char(strlen(ar));/*This certainly should not be here*/
Scptr.push(ar2);
cout<<Scptr.pop();//Doesn't print anything
return 0;
}
When I do this :
#include<iostream>
using namespace std;
template<class T> class Stack{
public:
Stack() : top(0){}
void push(T []);
T pop();
private:
int top;
T array[10] ;
};
template<class T>T Stack<T>::pop(){
assert(top > 0);
return (array[--top]);
}
template<class T>void Stack<T>::push(T ele[]){
assert(top < 10);
array[top] = new char (strlen(ele)); //mem allocation
strcpy(array[top], ele);
top++;
}
int main(){
Stack<char*> Scptr;
char ar[] = "abhi";
Scptr.push(ar);
cout<<"Popped : "<< Scptr.pop(); //can see the output!
}
works perfect!
@I am using a Dev C++ 4.9.9.2 compiler@