Jorje12
Jorje12

Reputation: 423

pointer array returns negative values

I am trying to calculate the arithmetic mean of the digits of a number from a number array.
I'm trying to use dynamic memory allocation and pointers.
I can't think of anything faster or better.

void media_cifrelor(int *p, int &x)
{
    int *w = new int[x];
    for (int i = 0; i < x; i++)
    {
        int k = 0;
        while (*(p + i) != 0)
        {
            k++;
            *(w + i) += *(p + i) % 10;
            *(p + i) /= 10;
        }
        *(w + i) /= k;
        cout << *(w + i) << " ";
        cout << endl;
    }
    cout << endl;
}

//p1.txt
// 7
// 12 231 9012 34 8123 22 507

int main()
{
    ifstream fisier("p1.txt");

    int n, *v;

    v = citire(fisier, n); // int *citire(ifstream &fisier, int &x)
    cout << "n= " << n << endl;

    // for (int i = 0; i < n; i++)
    // {
    //     cout << *(v + i) << " ";
    // }
    cout << endl;

    media_cifrelor(v, n);

    return 0;
}

cout << *(w + i) << " "; returns random negative values on each run and I do not understand where is the mistake.

Reading from file function:

int *citire(ifstream &fisier, int &x)
{
    if (fisier.is_open())
    {
        int *p;
        fisier >> x;
        // cout << "x= " << x << endl;
        p = new int[x];
        for (int i = 0; i < x; i++)
        {
            fisier >> *(p + i);
            // cout << *(p + i) << " ";
        }
        cout << endl;
        return p;
    }
    else
    {
        cout << "Could not open file" << endl;
        return 0;
    }
}

Upvotes: 0

Views: 272

Answers (1)

Adrian Mole
Adrian Mole

Reputation: 51845

You are not initializing the elements of the allocated w array, so each starts off with an arbitrary/random value. To fix this, set each of the *(w + i) elements to zero before you start accumulating the sums of the digits:

void media_cifrelor(int *p, int &x)
{
    int *w = new int[x]; // Note: this memory is NOT zero-initialized!
    for (int i = 0; i < x; i++)
    {
        int k = 0;
        *(w + i) = 0;    // ... so, we need to zero each value before summing.
        while (*(p + i) != 0)
        {
            k++;
            *(w + i) += *(p + i) % 10;
            *(p + i) /= 10;
        }
        *(w + i) /= k;
        cout << *(w + i) << " ";
        cout << endl;
    }
    cout << endl;
    delete[] w; // Note: Don't forget to release the allocated memory!
}

As noted in the comments, you could zero the elements of the w memory block by adding an empty initializer list:

    int* w = new int[x]{};

Better still, avoid 'old-style' new[] and delete[] operators and use: std::vector<int> w(x, 0);.

Upvotes: 1

Related Questions