c++ - 在函数中填充指针数组

标签 c++ arrays pointers

我的程序应该填满并显示一个数组。它还应该计算数组中的平均值。

程序停在这一行:

cin >> *f1[j];

我认为这是问题所在,但我可能在其他地方犯了错误。

#include <iostream>

using namespace std; 

// prototypes
void add(int*f[],int h);      
void show(int*f[],int h);
int average(int*f[],int h);

int main()
{
    // getting size of a array
    cout << "How many numbers would you insert? : ";
    int i = 0;
    cin >> i;
    cout << endl;

    // the dinamic array
    int * arr = new int[i]; 

    // call functions
    add(&arr, i);
    show(&arr, i);
    average(&arr, i);

    // deleting the dinamic array
    delete[] arr;
    system("pause");
    return 0;
}

// declaring of the functions

// this function should fill up the array
void add(int* f1[], int h)
{
    for(int j = 0 ; j < h ; j++)
    {
        cout << "Insert " << j+1 << ". value : ";
        cin >> *f1[j]; //this should be the problem
        cout << endl;
    }

}

// this function should show the array
void show(int *f2[], int h)
{
    for(int j = 0 ; j < h ; j++)
    {
        cout << *f2[j] << ", ";
    }
}

// this function should should show average value of the array
int average(int *f3[], int h)
{
    int n = 0;
    for(int j = 0 ; j < h ; j++)
    {
        n += *f3[j];
    }
    n /= h;
    return n;
}

最佳答案

您没有正确引用数组。 p* 指向索引p[0]

cout << *f2[j] << ", ";

应该是

cout << f2[j] << ", ";

它编译并运行我所做的编辑。

http://ideone.com/DsxOOP

此外,您没有接受任何输入。

关于c++ - 在函数中填充指针数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25210009/

相关文章:

c++ - 数字 xor K - K = 数字 + K xor K,为什么?

c++ - opencv 不识别宏

c++ - 为什么编译器不能推导模板模板参数?

c - 在 C 中将字符追加到字符数组

更改下一个指向结构的值

c++ - ‘->’ 的基本操作数具有非指针类型

c++ - Syntastic 提示文件丢失

php - 在 PHP 中获取数组的所有其他值

java - 将数组添加到 JTextField

c - 为什么 int *b[5] 形成 8 位的差异而不是 4 位?