Reputation: 122
void printMatrix(int matrix[][], int edge)
{
int i,j;
for (i=0; i<edge; ++i) {
for (j=0; j<edge; ++j) {
std:cout<<matrix[i][j]<<" ";
}
std::cout<<std::endl;
}
}
seems fine if i do in java, but in c++, it indicate Subscript of pointer to incomplete type 'int []'
Upvotes: 1
Views: 172
Reputation: 1136
using one dimentional array, as ls. and caculate the dimention by yourself
Upvotes: 2
Reputation: 13520
When you pass a multi-dimensional array to a function, you must fill in all its dimensions, except the first one. That is arr[][X], arr[][X][Y], ...
.
The compiler knows how to do the array locations math according to the dimensions. For example, arr[][5]
means every row contains 5 elements, so arr[2][0]
will take it 10 elements from the start. So the first dimension isn't necessary, but all the others - are.
Upvotes: 2
Reputation: 3165
If you have a square matrix, you can do it this way:
void printMatrix(int matrix[], int edge)
{
int i,j;
for (j=0; j<edge; ++j) {
for (i=0; i<edge; ++i) {
std:cout << matrix[j*edge + i] << " ";
}
std::cout << std::endl;
}
}
Essentially, store rows (or columns, it's up to you) one after another in a 1D array.
Note that the inner loop iterates over j
- this way the loop accesses consecutive cells in memory.
The rest of your code should then use the same convention.
This approach isn't the best if you're paid (or given points) for every class, template, design pattern etc. you add to your code, though.
Upvotes: 0
Reputation: 308530
C++ does not pass the size of an array or the number of dimensions, it only passes the address of the start of the array (i.e. a pointer). You can get around this by using a template function with a reference. This way the size of the matrix is known at compile time.
template<int X, int Y>
void printMatrix(int (&matrix)[X][Y], int edge)
{
int i,j;
for (i=0; i<edge; ++i) {
for (j=0; j<edge; ++j) {
std:cout<<matrix[i][j]<<" ";
}
std::cout<<std::endl;
}
}
Upvotes: 0
Reputation: 39471
You shouldn't use raw arrays at all. std::array
is much better. If you want the size to not be part of the type, you should use std::vector
. There are cases where you might need to use a raw array or raw pointer, but this isn't something you should be worrying about as a beginner.
Here's an example of how you might do things (assuming C++11 support). This uses const correctness and the new foreach feature as well. I don't remember the exact syntax but it should look something like this.
void printMatrix(const std::vector<std::vector<int>> matrix)
{
for(const auto& row : matrix){
for(int x : row){
std::cout << x << " ";
}
std::cout<<std::endl;
}
}
Upvotes: 1