正在从链接列表中检索字符

Retrieving chars from a linked list

本文关键字:检索 字符 列表 链接      更新时间:2023-10-16

C++问题。我已经成功地(经过一些研究:P)为一堆int创建了一个链表实现。不过,我在为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;
 }
}

感谢您阅读我的问题和/或您可以提供的任何澄清:)

您的类似乎还可以,但主要内容需要更改:

 // pushed strings are of an arbitrary, but always known, length
 char stringA[] = "foo";
 char stringB[] = "fooba";
 char stringC[] = "foobar ";
 linklistCommands commandList;
 commandList.push(stringA);
 commandList.push(stringB);
 commandList.push(stringC);
 while(commandList.isEmpty()!=1)
 {
  cout << commandList.pop() << endl;
 }

您应该考虑使用std::string而不是char*,这样更简单、更安全。另外,char[N]stringA="…";这是C#或Java语法,而不是C++

您必须分配和管理char*数据字段并复制输入值。:)(或者至少使用strdup())。您可能还想将const-char*视为输入数据的类型

我从我的手机发送,所以简短的回答:&用于获取当前元素的地址,*用于从地址中获取值。因此,通过两次使用*,您可以从指向值的地址的地址中获取值。