I'm working on a problem where I cannot use array indexing to change elements and I'm really struggling with pointers. This is code is supposed to initialize an array with all index initialized to 0, except for indexes 0 and 1. Indexes 0 and 1 are initialized to -1. The array I get back has weird numbers in it,
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;
}
new[], the memory will be uninitialized and have indeterminate contents. That makes the conditions in yourarrfunction invalid and have undefined behavior.arr) when the loop ends, thenthearraywill no longer point to the original location thatnew[]returned. The pointer you return will be invalid.*thearrayis exactly equal tothearray[0]. Secondly, if the value ofthearray[0]is indeterminate (and could be seen as random or garbage), then how could you use that value in a condition (like e.g.*thearray < last)? You can initialize the array, that's not a problem (std::fillorstd::fill_nare very helpful here) but you can't use the contents before that initialization.