gpt4 book ai didi

C++仅使用指针更改数组的元素

转载 作者:行者123 更新时间:2023-11-27 23:39:59 24 4
gpt4 key购买 nike

我正在解决一个问题,我无法使用数组索引来更改元素,而且我真的很难处理指针。这段代码应该初始化一个数组,所有索引都初始化为 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;
}

最佳答案

有几种方法可以将数组初始化为全零:

  • 使用值初始化

    int* thearray = new int[size]();
  • 使用 std::fill_n

    int* thearray = new int[size];
    std::fill_n(thearray, size, 0);
  • 使用 std::fill

    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);

如果您必须使用原始指针(由于赋值或练习条件),那么我建议使用前两种之一。

关于C++仅使用指针更改数组的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55916355/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com