中止陷阱 - 我的代码有问题
abort trap - something is wrong with my code
我正在在C 中开发链接列表。我使用delete
时有问题。
我阅读了程序参数中的元素数量。我可以创建它们。我可以列出它们。当我使用delete
时,代码不起作用。
我是否必须完全使用delete
?
#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
,但是我的代码中有问题。
我已经根据@yksisarvinen评论修复了我的代码。现在起作用。谢谢!
#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;
}
}
相关文章:
- 需要以下代码的帮助,下面的代码有什么问题
- 我关于函数"Assert"的C++代码有问题
- 标准对此指向成员函数类型模板参数有何说明?是我的代码有误,还是 MSVS 16.6 有问题?
- 以下 C++ 代码有什么问题?
- 继承此C++代码有什么问题
- 有谁知道这段代码有什么问题?
- C++ 回文程序总是给出 0(假)作为输出问题;我的代码哪里有问题?
- 这段简单的代码有什么问题?
- 这个随机字符串打印代码有什么问题?
- 我在 c++ 中的 AES 代码有问题。明文正在更改,但加密邮件是相同的。我找不到我的错误
- C++ 制作一个随机数字/字母生成器,代码中有问题
- 我的C++合并排序代码有什么问题?
- 我的转置矩阵代码有什么问题?
- 中止陷阱 - 我的代码有问题
- C++ 我的代码有问题
- 我的插入排序代码有问题
- 彩票应用程序,代码有问题
- 这怎么可能是竞态条件.或者是我的代码有问题
- C++:使用变量派生.一小部分代码有问题
- 我的代码有问题,因为我无法弄清楚为什么会收到错误。这是代码: