C++问题在这里。我已经成功(经过一番研究:P)为一堆整数创建了一个链表实现。我在修改char *的时候遇到了一些麻烦......从链接列表中检索字符
我认为这可能只是一个问题,与我在下面定义的linklistCommands类使用的函数有关的引用/取消引用指针。 (我一直无法理解什么时候使用&或*与参数和返回值有关。)我已经评论了我的代码中可能混淆的行。
不管怎么说,这里是我的代码至今:
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;
}
}
感谢您在我的问题和/或任何澄清您可以提供:)
请注意,如果你的stringA,stringB等超出范围(它们不会在主体中,但它们可能会在另一个函数中声明),它们将在任何地方停止存在(以及它们可能会也可能不会,这取决于你的程序正在做的基本上不相关的其他事情),并且如果它们稍后弹出,你的堆栈将返回垃圾。使用std :: string会阻止这一点。 – Brilliand 2012-03-10 08:04:55
啊。 StringA,stringB不是我实际代码的一部分,而只是在那里放置。至于我的实际变量,我正在管理那些从未被超出范围的内存。 – zedadex 2012-03-10 10:35:56
chac,我可以/不应该在C++中使用char [N]吗?我在那里输入char [N]只是为了表明字符串长度可以变化,但长度是已知的,但我的实际代码没有将字符串初始化为它们的最终值 - 它们相当于在时间,从一个循环。 – zedadex 2012-03-10 10:38:06