0

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;
}
11
  • 1
    When you allocate memory with new[], the memory will be uninitialized and have indeterminate contents. That makes the conditions in your arr function invalid and have undefined behavior. Commented Apr 30, 2019 at 8:06
  • 1
    Furthermore (also in the function arr) when the loop ends, then thearray will no longer point to the original location that new[] returned. The pointer you return will be invalid. Commented Apr 30, 2019 at 8:08
  • I'm not sure I understand. Commented Apr 30, 2019 at 8:18
  • arr is supposed to return an initialized array and I dont know how to do that without new[] Commented Apr 30, 2019 at 8:20
  • First of all, *thearray is exactly equal to thearray[0]. Secondly, if the value of thearray[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::fill or std::fill_n are very helpful here) but you can't use the contents before that initialization. Commented Apr 30, 2019 at 8:27

2 Answers 2

2

There are a few ways to initialize your array to all zeros:

  • Use value initialization

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

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

    int* thearray = new int[size];
    int* end = thearray + size;
    std::fill(thearray, end, 0);
    
  • Use pointers and explicit loops

    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
    
  • Use std::vector instead

    std::vector<int> thearray(size);
    

If you must use raw pointers (due to the assignment or exercise conditions) then one of the first two is what I recommend.

Sign up to request clarification or add additional context in comments.

Comments

1

Solution 1 - just use std::vector

The simple way to do this is to use std::vector, because std::vector makes life easy. You don't have to delete it, and it keeps track of it's length (call .size() to get the number of elements).

We can write arr pretty simply now:

std::vector<int> arr(int size) {
    std::vector<int> vect(size); // Everything initialized to 0
    vect[0] = -1;
    vect[1] = -1;
    return vect; 
}

Solution 2 - default-initialize the array

Write now, you have

int* thearray = new int[size];

This leaves the memory uninitialized. We can initialize it to 0 just by adding a () after new int[size]:

int* thearray = new int[size](); // array initialized to 0

We can rewrite arr like this:

int* arr(int size) {
    int* thearray = new int[size]();
    thearray[0] = -1;
    thearray[1] = -1;
    return thearray;
}

Solution 3 - use pointers on an uninitialized array.

Ok ok. So maybe you're into pointers, or maybe you're a student and your professor is evil. We can use them.

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
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.