【发布时间】:2016-11-06 16:37:56
【问题描述】:
当我尝试删除动态分配的数组时,我的程序不断崩溃。当我调试程序时出现此错误:
#0 0x47a949 std::basic_ostream<char, std::char_traits<char> >& std::operator<< <char, std::char_traits<char>, std::allocator<char> >(std::basic_ostream<char, std::char_traits<char> >&, std::basic_string<char, std::char_traits<char>, std::allocator<char> > const&) () (??:??)
#1 0x48a940 std::cerr () (??:??)
#2 0x722924 ?? () (??:??)
#3 0x4010fd __mingw_CRTStartup () (??:??)
#4 0x7729cf34 strerror_s() (C:\WINDOWS\SysWoW64\msvcrt.dll:??)
#5 0x775d0719 ?? () (??:??)
#6 0x775d06e4 ?? () (??:??)
#7 ?? ?? () (??:??)
这是我的代码:
#include <iostream>
#include <string>
#include <stdlib.h>
using namespace std;
int main()
{
int numNames;
cout << "How many names do you want to enter?" << endl;
cin >> numNames;
std::string *names = new (nothrow) std::string[numNames];
if (!names)
{
std::cout << "Could not allocate memory";
exit(EXIT_FAILURE);
}
for (int i = 0; i <= numNames-1; i++)
{
cout << "Enter name #" << i+1 << endl;
cin >> names[i];
}
for (int start = 0; start < numNames; start++)
{
int smallestName = start;
for (int currentName = start + 1; currentName < numNames; currentName++)
{
if (names[currentName] < names[smallestName])
{
smallestName = currentName;
}
}
swap(names[start], names[smallestName]);
}
cout << endl << "Here is your sorted list: " << endl;
for (int i = 0; i <= numNames; i++)
{
cout << names[i] << endl;
}
delete[] names;
names = nullptr;
return 0;
}
我尝试了两个名称 = 0;和名称= nulltptr;他们都没有工作。 我希望你能帮我找到我的问题。 干杯!
【问题讨论】:
-
调试器是解决此类问题的正确工具。 在询问 Stack Overflow 之前,您应该逐行浏览您的代码。如需更多帮助,请阅读How to debug small programs (by Eric Lippert)。至少,您应该 [编辑] 您的问题,以包含一个重现您的问题的 Minimal, Complete, and Verifiable 示例,以及您在调试器中所做的观察。
-
在你的最后一个 for 循环中 ... i
-
当我尝试它时效果很好,什么值会崩溃
-
@πάνταῥεῖ 不,他的调试器是解决这个特殊问题的完全错误的工具。
-
你真的应该试试modern C++ techniques。当您自己发现问题所在时,您的生活会更轻松。
标签: c++ arrays dynamic delete-operator