編譯器報錯:choice: 未聲明的標識符、delete: 不能刪除不是指針的對象。程式碼中在 while 迴圈內部用 new 動態配置陣列,但在迴圈外嘗試 delete[],導致作用域問題。
int _tmain(int argc, _TCHAR* argv[])
{
// ...
while(1)
{
// ...
int *choice = new int[num_choice]; // 區域變數,作用域僅限 while 區塊
double *quantity_choice = new double[num_choice];
// ...
} // 這裡 choice、quantity_choice 已離開作用域,無法在外部 delete
delete[] choice; // 錯誤:找不到 choice
choice = NULL;
delete[] quantity_choice; // 錯誤:同上
// ...
}
int _tmain(int argc, _TCHAR* argv[])
{
int *choice = nullptr; // 1. 宣告於外部
double *quantity_choice = nullptr;
while(1)
{
// ...
choice = new int[num_choice]; // 2. 僅配置,不重複 int*
quantity_choice = new double[num_choice];
// 使用 choice、quantity_choice...
// 若迴圈可能多次執行,記得先 delete 舊記憶體再新配置
// delete[] choice;
// choice = new int[num_choice];
}
delete[] choice; // 3. 迴圈外可正常釋放
choice = nullptr;
delete[] quantity_choice;
quantity_choice = nullptr;
// ...
}
// cal 函數補上 default
double cal(int num, double quantity)
{
switch(num)
{
case 0: return quantity * 1.50;
// ... 其他 case ...
default: return 0.0; // 防止無返回值
}
}
{} 為界,迴圈內宣告的變數迴圈結束即銷毀。delete[] 只能釋放由 new[] 配置的記憶體,且指標必須在作用域內。nullptr,釋放後設為 nullptr,防止野指標。