-1
當我嘗試刪除動態分配數組時,我的程序一直崩潰。當我調試程序這個錯誤出現:刪除動態數組時發生崩潰
#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;和names = nulltptr;他們都沒有工作。 我希望你能幫我找到我的問題。 乾杯!
解決此類問題的正確工具是您的調試器。在*堆棧溢出問題之前,您應該逐行執行您的代碼。如需更多幫助,請閱讀[如何調試小程序(由Eric Lippert撰寫)](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/)。至少,您應該\編輯您的問題,以包含一個[最小,完整和可驗證](http://stackoverflow.com/help/mcve)示例,該示例再現了您的問題,以及您在調試器。 –
在你最後一個for循環中...我<= numNames ..應該是..我
HazemGomaa
當我嘗試它時,工作正常,什麼值會使它崩潰 –