首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >中止陷阱-我的代码有问题

中止陷阱-我的代码有问题
EN

Stack Overflow用户
提问于 2019-05-26 22:38:37
回答 1查看 43关注 0票数 1

我正在用C++开发链表。我在使用delete时遇到了问题。

我从程序参数中读取元素的数量。我可以创建它们。我可以把它们列出来。当我使用delete时,代码无法工作。

我一定要使用delete吗?

代码语言:javascript
复制
#include <iostream>
#include <sstream>

struct element {
  int value;
  element *next;
};

int main(int argc, char **argv) {

  int num;
  std::stringstream ss;

  if (argc >= 2) {
    std::cout << argv[0] << std::endl;
    ss << argv[1];
    ss >> num;
    std::cout << "You want: " << num << " numbers" << std::endl;
  } else {
    std::cout << "Error" << std::endl;
  }

  element *first = NULL;
  element *current = NULL;


  // creating
  for(int i=0; i<num; i++) {
    element *elem = new element();
    if( first == NULL ) {
      first = elem;
    }

    elem -> value = i;
    elem -> next = NULL;

    if( current == NULL ) {
      current = elem;
    } else {
      current -> next = elem;
      current = elem;
    }
  }

  // printing
  current = first;
  while( current ) {
    std::cout << "value: " << current -> value << std::endl;
    current = current -> next;
  }

  // removing
  current = first;
  while( current ) {
    delete current;
    current = current -> next;
  }

  delete first;

}

我想要的是打印所有元素。我知道每个new都应该伴随着delete,但是我的代码中有错误。

EN

回答 1

Stack Overflow用户

发布于 2019-05-27 22:46:25

我已经基于@Yksisarvinen注释修复了我的代码。它现在起作用了。谢谢!

代码语言:javascript
复制
#include <iostream>
#include <sstream>

struct element {
  int value;
  element *next;
};

int main(int argc, char **argv) {

  int num;
  std::stringstream ss;

  if (argc >= 2) {
    std::cout << argv[0] << std::endl;
    ss << argv[1];
    ss >> num;
    std::cout << "You want: " << num << " numbers" << std::endl;
  } else {
    std::cout << "Error" << std::endl;
  }

  element *first = NULL;
  element *current = NULL;


  // creating
  for(int i=0; i<num; i++) {
    element *elem = new element();
    elem -> value = i;
    elem -> next = NULL;

    if( current == NULL ) {
      first = elem;
      current = elem;
    } else {
      current -> next = elem;
      current = elem;
    }
  }

  // printing
  current = first;
  while( current ) {
    std::cout << "value: " << current -> value << std::endl;
    current = current -> next;
  }

  // removing
  current = first;
  while( current ) {
    element *to_remove = current;
    current = current -> next;
    delete to_remove;
  }
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56314479

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档