我正在解决一个问题,即我无法使用数组索引来更改元素,而我真的在指针方面苦苦挣扎。该代码应该用来初始化一个数组,其中所有索引都初始化为0(索引0和1除外)。索引0和1初始化为-1。我返回的数组中有奇怪的数字,
int* arr(int size);
int main()
{
int low, high;
char again = 'y';
high = low = 0;
cout << "\tThe Sieve of Eratosthenes" << endl << endl;
do
{
do
{
cout << "Enter the high boundary: ";
cin >> high;
cout << endl;
if (high <= 0)
cout << "ERROR: HIGH BOUNDARY MUST BE POSITIVE" << endl;
} while (high < 0);
int* thearr = arr(high);
cout << "The prime numbers from to " << high << " are: " << endl;
for (int ix = 0; ix <= high; ++ix)
{
cout << thearr[ix] << " ";
}
cout << endl << endl;
cout << endl << endl;
cout << "Try again with new boundaries? (y/n):" << endl;
cin >> again;
delete[] thearr;
} while (again == 'y');
return 0;
}
int* arr(int size)
{
int* thearray = new int[size];
int last = size;
cout << *thearray << " " << last;
while (*thearray < last)
{
if (*thearray <= 1)
thearray[*thearray] = 0;
else
thearray[*thearray] = -1;
++thearray;
cout << *thearray;
}
return thearray;
}
答案 0 :(得分:2)
有几种方法可以将数组初始化为全零:
使用值初始化
int* thearray = new int[size]();
int* thearray = new int[size];
std::fill_n(thearray, size, 0);
int* thearray = new int[size];
int* end = thearray + size;
std::fill(thearray, end, 0);
使用指针和显式循环
int* thearray = new int[size];
int* end = thearray + size;
int* begin = thearray;
while (begin < end)
{
*begin++ = 0;
}
// After loop thearray still points to the beginning of the array
改为使用std::vector
std::vector<int> thearray(size);
如果您必须使用原始指针(由于作业或锻炼条件),那么我建议您使用前两个指针之一。
答案 1 :(得分:1)
std::vector
执行此操作的简单方法是使用std::vector
,因为std::vector
使生活变得轻松。您不必删除它,它就会跟踪它的长度(调用.size()
以获取元素数)。
我们现在可以很简单地写arr
:
std::vector<int> arr(int size) {
std::vector<int> vect(size); // Everything initialized to 0
vect[0] = -1;
vect[1] = -1;
return vect;
}
现在写,你有
int* thearray = new int[size];
这将使内存未初始化。我们可以通过在()
之后添加new int[size]
来将其初始化为0:
int* thearray = new int[size](); // array initialized to 0
我们可以这样重写arr
:
int* arr(int size) {
int* thearray = new int[size]();
thearray[0] = -1;
thearray[1] = -1;
return thearray;
}
好的,好的。因此,也许您陷入困境,或者您是一名学生,而您的教授却是邪恶的。我们可以使用它们。
int* arr(int size) {
int* vals = new int[size]; // Create the array
// We need to return the ORIGINAL pointer (which is vals)
// because we need to return the original pointer, we're gonna use a
// a new pointer called 'scan' to modify the array
int* scan = vals;
*scan = -1; // Set the value at scan to -1 (this is vals[0])
scan += 1; // move scan to the next value in the array
*scan = -1; // Do it again for vals[1]
scan += 1;
// Set the rest of the values to 0
for(int i = 2; i < size; i++) {
*scan = 0; // set the value to 0
scan += 1; // move to the next value
}
return vals; // Return the ORIGINAL pointer
}