C ++ error: invalid types 'int [int]' for array index

An attempt to learn C ++ and work with a simple exercise on arrays.

Basically, I created a multidimensional array, and I want to create a function that outputs values.

The commented for-loop in Main () works fine, but when I try to turn this for-loop into a function, it will not work, and for life I donโ€™t understand why.

#include <iostream>
using namespace std;


void printArray(int theArray[], int numberOfRows, int numberOfColumns);

int main()
{

    int sally[2][3] = {{2,3,4},{8,9,10}};

    printArray(sally,2,3);

//    for(int rows = 0; rows < 2; rows++){
//        for(int columns = 0; columns < 3; columns++){
//            cout << sally[rows][columns] << " ";
//        }
//        cout << endl;
//    }

}

void printArray(int theArray[], int numberOfRows, int numberOfColumns){
    for(int x = 0; x < numberOfRows; x++){
        for(int y = 0; y < numberOfColumns; y++){
            cout << theArray[x][y] << " ";
        }
        cout << endl;
    }
}
+3
source share
4 answers

C ++ inherits its syntax from C and tries to maintain backward compatibility where the syntax matches. Thus, passing arrays work just like C: length information is lost.

++ ( , C ):

template<int numberOfRows, int numberOfColumns>
void printArray(int (&theArray)[numberOfRows][numberOfColumns])
{
    for(int x = 0; x < numberOfRows; x++){
        for(int y = 0; y < numberOfColumns; y++){
            cout << theArray[x][y] << " ";
        }
        cout << endl;
    }
}

: http://ideone.com/MrYKz

, : http://ideone.com/GVkxk

, . , C ++ .

, : http://ideone.com/kjHiR

+5

theArray , ( ):

void printArray(int theArray[][3], int numberOfRows, int numberOfColumns);
+2

, , . , . , printArray

void printArray(int theArray[][3], int numberOfRows, int numberOfColumns){
    for(int x = 0; x < numberOfRows; x++){
        for(int y = 0; y < numberOfColumns; y++){
            cout << theArray[x][y] << " ";
        }
        cout << endl;
    }
}
0

, , . ++ (. std::vector std::array), , printArray :

printArray(sally, 2, 3);

:

void printArray(int* theArray, int numberOfRows, int numberOfColumns){
    for(int x = 0; x < numberOfRows; x++){
        for(int y = 0; y < numberOfColumns; y++){
            cout << theArray[x * numberOfColumns + y] << " ";
        }
        cout << endl;
    }
}

, :

  • the function takes a pointer, so you pass in the name of the multidimensional array, which is also the address for its first element.

  • as part of the index ( theArray[x * numberOfColumns + y]) operation, we refer to a sequential element that thinks of a multidimensional array as a unique array of strings.

0
source

All Articles