这是我的代码:
int main ()
{
const int MAX = 10;
char *buffer = nullptr; // used to get input to initialize numEntries
int ARRAY_SIZE = 20; // default is 20 entries
int numEntries;
success = false;
while (!success)
{
delete buffer;
buffer = nullptr;
buffer = new char [MAX];
cout << "How many data entries:\t";
cin.getline(buffer, MAX, '\n');
cout << endl << endl;
while (*buffer)
{
if (isdigit(*buffer++))
success = true;
else
{
success = false;
break;
}
}
}
numEntries = atoi(buffer);
问题在于,当我输入任意数字时,它只显示“numEntries = 0”,如果输入字符串,它会崩溃。
有人可以解释究竟发生了什么吗?
答案 0 :(得分:0)
这是你的问题:
+----+----+----+----+----+
| | | | | |
+----+----+----+----+----+
^ ^
| |
Start End
Start
是从new []
表达式返回的指针。while (*buffer)
迭代地将指针移动到End
表示的位置。End
传递给delete
。这是错的。 Start
希望传递给delete
。您可能想要做的是存储第二个指向new []
表达式的结果,该表达式将与delete
一起使用(也应该是delete []
)例如:
int main ()
{
const int MAX = 10;
char *buffer = nullptr; // used to get input to initialize numEntries
char *bufferptr = nullptr; // <- ADDED
int ARRAY_SIZE = 20; // default is 20 entries
int index = 0;
success = false;
while (!success)
{
delete [] bufferptr; // <- CHANGED
buffer = nullptr;
buffer = new char [MAX];
bufferptr = buffer; // <- ADDED
cout << "How many data entries:\t";
cin.getline(buffer, MAX, '\n');
cout << endl << endl;
while (*buffer)
{
if (isdigit(*buffer++))
success = true;
else
success = false;
}
}
}