Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

generating an integer array

Tags:

c++

visual-c++

i am new to c++ and i want to write a program to generate an integer array. I keep getting the error at line

test[i][j]=i;

invalid types 'int[int]' for array 

Can anyone tell me what's wrong here? Thanks in advance.

int main()
{
    int rows;
    int cols;
    cin>>rows>>cols;
    int test[rows][cols];
    get_test(rows,cols,&test[0][0]);
    cout<<test[1][1]<<endl;
    return 0;
}

int get_test(int rows,int cols,int *test)
{ 
    int h=rows;
    int w=cols;
    int i=0,j=0;

    for(i=0;i<h;i++)
    {
        for (j=0;j<w;j++)
        {
            test[i][j]=i;
        }
    }

    return 0;
}
like image 246
newww0 Avatar asked Jul 12 '26 05:07

newww0


1 Answers

int test[rows][cols]; with non compile time value is a variable length array which is a possible extension of some compilers.

Prefer using std::vector instead:

int get_test(std::vector<std::vector<int>>& test)
{ 
    for (int i = 0;i != test.size(); ++i)
    {
        for (int j = 0; j != test[i].size(); ++j)
        {
            test[i][j] = i;
        }
    }
    return 0;
}

int main()
{
    int rows;
    int cols;
    cin>>rows>>cols;
    std::vector<std::vector<int>> test(rows, std::vector<int>(cols));
    get_test(test);
    cout << test[1][1] << endl;
    return 0;
}
like image 89
Jarod42 Avatar answered Jul 13 '26 19:07

Jarod42



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!