【发布时间】:2018-04-03 20:33:44
【问题描述】:
该程序应该从用户输入中获取一个数组并将其拆分为两个数组,分别用于负值和非负值。
该程序的工作原理包括
count(userList, n, numPos, numNeg);
当我声明时抛出错误
int *negList = new int[numNeg];
int *posList = new int[numPos];
我想把它改成
int *negList;
negList = new int[numNeg];
int *posList;
posList = new int[numPos];
可以解决问题,但不能。
之前的声明int *userList;
userList = new int[n];
不会抛出任何错误。
这发生在 Windows 上的 Codeblocks 以及带有 g++ 的 Linux 上。
整个代码如下:
#include <iostream>
using namespace std;
//count positive and negative elements in list
void count(const int* arr/*list*/, int numElements/*num elements in array*/, int& numPos/*num positive elements*/, int& numNeg/*num negative elements*/);
int main()
{
//declare variables
int n; //number of elements
int userInput; //place holder for list values
int numPos; int numNeg; //num positive and negative elements
//prompt user for number of elements
cout << "Enter number of elements: ";
cin >> n;
//declare array
int *userList;
userList = new int[n];
//prompt user for list and read in
cout << "Enter list: " << endl;
cin >> userInput;
for(int i(0); i < n; i++){
cin >> userInput;
}
//count positive and negative elements
count(userList, n, numPos, numNeg);
//declare arrays for negative and positive elements respectively
int *negList = new int[numNeg];
int *posList = new int[numPos];
// ...
//free memory
delete [] userList;
delete [] negList;
delete [] posList;
return 0;
}
void count(const int* arr, int numElements, int& numPos, int& numNeg)
{
for(int i(0); i < numElements; i++){
if(arr[i] < 0){
numNeg++;
}
else{
numPos++;
}
}
}
非常感谢所有帮助!
【问题讨论】:
-
您使用的
n有多大?分配如此大量的连续内存可能是不可能的 -
在使用前我没有看到
numNeg的任何初始化。