在第 18 行出现关于我的 2D 数组的奇怪错误(错误:数组下标的类型“int[int]”无效)

问题描述 投票:0回答:1

在一个单独的函数中,程序接受用户输入的二维数组的行数和列数。然后,我使用嵌套循环让用户用整数填充数组。当我运行程序时,在获取整数的行上出现错误( cin>>nums[i][j]; )。我收到的错误是 error: invalid types 'int[int]' for array subscripts.

#include <iostream>

using namespace std;

// function to get the user input
void getValues(int &nums, int r, int c)
{
    //get number of rows and columns from user
    cout<<"Enter the number of rows: ";
    cin>>r;
    cout<<"Enter the number of columns: ";
    cin>>c;

    // ask use to fillout the array
    for(int i = 0; i < r; i++)
    {
        for(int j = 0; j < c; j++)
        {
            cout<<"Enter a number for the array: ";
            cin>>nums[i][j]; // ***ERROR IS HERE***
        }
    }
}

// display the 2D array
void display()
{

}

int main()
{
    int r;
    int c;
    int user;
    int nums[r][c];
    
    cout<<"1. Input values"<<endl;
    cout<<"2. Display values"<<endl;
    cout<<"3. get sum of all values"<<endl;
    cout<<"4. get row-wise sum of array"<<endl;
    cout<<"5. get column-wise sum of array"<<endl;
    cout<<"6. Transpose array"<<endl;
    cout<<"7. Exit"<<endl;
    cout<<"Chose an option (Enter option number): ";
    cin>>user;

    if(user == 1)
    {
        getValues(nums[r][c], r, c);
    }
    return 0;

}
c++ console-application
1个回答
0
投票

您没有将实际的数组传递给“getValues()”函数,您只是简单地传递了一个 int。另外,将指针传递给函数(我假设这就是您想要做的)被写为“void foo(int *num)”。

// function to get the user input
void getValues(int **(nums), int r, int c)
{
    // ask use to fillout the array
    for(int i = 0; i < r; i++)
    {
        for(int j = 0; j < c; j++)
        {
            cout<<"Enter a number for the array: ";
            cin>> nums[i][j];
        }
    }
}

输入行和列的过程已移至主函数,以便您正确设置二维数组。我在这篇文章中使用了方法 3 来创建 2D 数组,因为这允许您传递给它的函数不定义它所获取的数组的大小。这也允许它具有指针的功能,因此更改“getValues()”函数中的值会更改它们在内存中的内容。

int main()
{
    int r;
    int c;
    int user;
    
    cout<<"1. Input values"<<endl;
    cout<<"2. Display values"<<endl;
    cout<<"3. get sum of all values"<<endl;
    cout<<"4. get row-wise sum of array"<<endl;
    cout<<"5. get column-wise sum of array"<<endl;
    cout<<"6. Transpose array"<<endl;
    cout<<"7. Exit"<<endl;
    cout<<"Chose an option (Enter option number): ";
    cin>>user;
    
    //get number of rows and columns from user
    cout<<"Enter the number of rows: ";
    cin>>r;
    cout<<"Enter the number of columns: ";
    cin>>c;
    
    //Create a 2D array
    int **nums = new int*[c];
    
    //Define all the inner dimensions as int[]'s with the size c
    for(int i = 0; i < r; i++)
    {
        nums[i] = new int[c];
    }

    if(user == 1)
    {
        getValues(nums, r, c);
    }
    
    cout << "nums[0][0] = " << nums[0][0];
    
    return 0;

}
© www.soinside.com 2019 - 2024. All rights reserved.