【问题标题】:pointer array returns negative values指针数组返回负值
【发布时间】:2021-03-04 15:40:11
【问题描述】:

我正在尝试计算数字数组中数字的算术平均值。
我正在尝试使用动态内存分配和指针。
我想不出更快或更好的方法。

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 &lt;&lt; *(w + i) &lt;&lt; " "; 每次运行都会返回随机负值,我不明白错误在哪里。

从文件中读取函数:

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

【问题讨论】:

    标签: c++


    【解决方案1】:

    您没有初始化分配的w 数组的元素,因此每个元素都以任意/随机值开始。要解决此问题,请在开始累积数字总和之前将每个 *(w + i) 元素设置为零:

    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!
    }
    

    如 cmets 中所述,您可以通过添加一个空的初始值设定项列表将 w 内存块的元素归零:

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

    更好的是,避免使用“旧式”new[]delete[] 运算符并使用:std::vector&lt;int&gt; w(x, 0);

    【讨论】:

    • new int[x]{}; 甚至std::vector&lt;int&gt; w(x);(以避免内存泄漏)。
    • 但事实上,无论如何我们都不需要数组,int k = 0; 之后的int w = 0; 可能就足够了(并将*(w + i) 替换为w)。
    • 另外,使用std::unique_ptr 应该优于手动delete
    • @SergeyA 但是,如果考虑使用 STL,我觉得 std::vector 更好。
    • @Jorje12 对于p 数组(在citire 函数中),您没有使用“随机”初始值。相反,您直接在fisier &gt;&gt; *(p + i); 行中分配它们。因此,最初存在的内容会被覆盖。但是,对于 w 数组,您假设它从零开始,然后使用 += 运算符添加到它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-05-30
    • 2018-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-05
    相关资源
    最近更新 更多