Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
167 views
in Technique[技术] by (71.8m points)

c++ - how to create LLL of char arrays

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,'
');
  head = head->next;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I assume this code:

while(again)
    build(head);

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

while(again())
    build(head);

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

head->next = new node;

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...