4

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?

3
  • arr[a] is a char. You cannot do [i] on a char. I guess you meant to pass a 2-D array instead of char arr[] Commented Nov 26, 2015 at 5:43
  • Ahh, that's probably my issue. I'll post an answer to this once I figure out the proper syntax. Commented Nov 26, 2015 at 5:45
  • It'd help if you post where you define and initialize your matrix Commented Nov 26, 2015 at 5:48

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.