C++ question here. I’ve successfully (after some research :P) created a linked-list implementation for a stack of ints. I’m having some trouble modifying it for char*’s though…
I think it may just be an issue with referenceing/dereferencing pointers in relation to the functions used by the linklistCommands class I have defined below. (I’ve always had trouble understanding when to use & or * in relation to arguments and return values.) I’ve commented the lines in my code that I probably muddled up.
Anyways, here is my code thus far:
struct linkc { // one 'link', stores a pointer to a char array
char * value;
linkc *next;
};
class linklistCommands
{
public:
linklistCommands()
{top = NULL;}
~linklistCommands()
{}
void push(char * address) // Pretty sure I'm OK here.
{
linkc *temp = new linkc;
temp->value = address;
temp->next = top;
top = temp;
}
char* pop() // Pretty sure I have to change something on this line
{
if (top == NULL)
return 0;
linkc * temp;
temp = top;
char * value;
value = temp->value;
top = temp->next;
delete temp;
return value;
}
bool isEmpty()
{
if (top == NULL)
return 1;
return 0;
}
private:
linkc *top;
};
int main(void)
{
// pushed strings are of an arbitrary, but always known, length
char[4] stringA = "foo";
char[6] stringB = "fooba";
char[8] stringC = "foobar ";
linklistCommands commandList;
commandList.push(stringA);
commandList.push(stringB);
commandList.push(stringC);
while(commandList.isEmpty!=1)
{
cout << (*commandList.pop()) << endl;
}
}
Thanks for reading through my question and/or any clarification you can provide 🙂
your class seems ok, but the main needs to be changed:
You should consider to use std::string instead of char*, it’s easier and safer.
Also, char[N] stringA = “…”; it’s C# or Java syntax, not C++