问题
I'm working on a program that does some matrix math. Fortunately the code logic is not what is giving me the errors.
I am using the following code to output a matrix that is stored in a 2-d array:
void ouputMatrix(char arr[], int matrixRows, int matrixColumns) {
for (int a=0; a<matrixRows; a++) {
for (int i=0; i<matrixColumns; i++) {
cout << arr[a][i] << " ";
}
cout << endl;
}
cout << endl;
}
However when I try to compile this code, I am told:
"In function 'void outputMatrix(char*, int, int)': [Error] Invalid types 'char[int]' for array subscript.
The error type suggests to me that I am missing something obvious with regards to c++ array syntax or something like that but I cannot figure it out. What am I doing wrong?
回答1:
If you would try to pass a 1-D array to function like this then its perfect what you did, but in case you are trying to pass 2-D array then u need to pass the array with its valid syntax, which is not just like the 1-D
i.e. return_type function_name(dataType arrayName[100],int size)
in case you can also leave the subscripts '[]' as blank for 1-D array ONLY,
but for 2-D array it would be
return_type function_name(dataType arrayName[100][100],int rowSize,int colSize)
however you can also leave the subscripts '[]' to be blank here also but only the 1st [] and 2nd must have to contain some value in it. actually it doesn't matter what value you passed in 2nd subscripts, but some value should has to be there, just pass a value to which your 2-D array would not exceed.
And the syntax will keep going like this for further dimensions of array. Hope this will work for you.
回答2:
The issue was that I was trying to pass a multidimensional array into the function but used the same syntax as I would for a 1-d array. Since the array has a size of 100 (which isn't something you could know based on my question, sorry...) the correct way to pass it is:
void ouputMatrix(char arr[][100], int matrixRows, int matrixColumns);
来源:https://stackoverflow.com/questions/33931320/compile-error-invalid-types-charint-for-array-subscript