本文介绍了如何创建char数组的LLL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

似乎每个指南是如何创建LLL与ints,但我有麻烦使用字符指针。当我运行这个代码,它会立即segfaults

it seems like every guide is how to create LLL with ints, but I'm having trouble using char pointers. when i run this code, it segfaults immediately

这里是我的代码到目前为止

here's my code thus far

struct node    
{
  char * data;
  node * next;   
};

void build(node * head);//create list    
void manipulate(node * & head);//manipulate list    
void display(node * head);//display all    
void delete_list(node * head);//delete all nodes in linked list    
bool again();//asks user if they'd like to continue

int main()
{
  node * head = NULL;
  //create list from user1 input
  while(again)
    build(head);
  //displays list
  display(head);
  //manipulate list as user2 reads through it
  manipulate(head);

  return 0;
}

void build(node * head)
{
  head->next = new node;
  char * data = new char;
  cout << "where to visit? ";
  cin.get(head->data,strlen(data)+1,'\n');
  head = head->next;
}


推荐答案

/ p>

I assume this code:

while(again)
    build(head);

原来是(再次调用 比较为零):

Was meant to be (calling again instead of comparing it to zero):

while(again())
    build(head);

无论哪种方式,第一次通过循环 head 为NULL。但 build 继续使用它:

Either way, the first time through the loop head is NULL. But build goes ahead and uses it anyway:

head->next = new node;

这里,使用 next 因为 head 为NULL。您正在访问内存中的无效位置。

Here, using next will produce a segment fault because head is NULL. You are accessing an invalid location in memory.

这篇关于如何创建char数组的LLL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 10:44