简体   繁体   中英

Pass a 2D Array Index into a Function?

I have a loop that populates a 2D array, and I want to pass the values created by this population, into a function to do other calculations with it. I'm a beginner at C++, so clear explanations would help a lot. Here is my code:

for (int car = 1; car <= 27; car++) {

    int test[27][3] = {{car, mpg[car], speed[car]}};

    float speed = speed[car];

    timeGen(speed);

    cout << car << "\t" << mpg[car] << "\t" << speed[car] << endl;
}

This is the timeGen function:

float timeGen(float x)
{
int distance = 50;
float speed = x;
float time = distance/x;
return time;
}

It seems as though everything will work fine, but what happens is that I get an error saying "subscript requires array or pointer type." I'm a little confused as to what they mean. Is it telling me to create a pointer to this index, and then call the pointer in the timeGen function? An explanation would be great!

Thank you very much. Also, the values mpg , speed , are taken from another part of my code which works fine. Instructions on how to fix the issue I'm having right now, would be great!

Even if you have an array named speed before defining float speed , it goes out of scope right after this definition. Try this:

float Cur_speed = speed[car];
timeGen(Cur_speed);

or

timeGen(speed[car]); // without the float speed

Another thing is, at each iteration you are creating a new instance of test . It looks like what you really want is to have a single test array:

int test[27][3];
for (int car = 0; car < 27; car++) {
 test[car][0] = car;
 test[car][1] = mpg[car];
 test[car][2] = speed[car];

Make sure that mpg is an array with 27 elements, and always use indices from 0 to 26. Same for the speed array. When we say test[car][0] , we mean the first element of test[car] , which has a total of 3 elements due to your definition. Essentially, the lines test[car][X] = Y; do the same thing you want to do with test[27][3] = {{car, mpg[car], speed[car]}} , however that syntax only works when you first declare an array. And the way you write it initializes all 27 elements with the same data.

You need to define float car_speed rather than float speed . It will resolve your error.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM