c++ - What is going wrong with my multidimentional array function? -
here have problem. want manipulate following matrix
matrix = 1---------2----------3
4---------5----------6
7---------8----------9
into
7---------8----------9
4---------5----------6
1---------2----------3
#include<iostream> using namespace std; void f(int arrayname, int size); int main() { int x[3][3]={{1,2,3}, {4, 5,6},{7,8,9}}; f(x, 3); system("pause"); } void f(int arrayname, int size) { int holder; for(int i=0; i<size; i++){ for(int j=0; j<size; j++) { holder=arrayname[i][j]; arrayname[i][j]=arrayname[i+2][j+2]; arrayname[i+2][j+2]=holder; } } for(int k=0; k<size; k++) for(int l=0; l<size; l++) { cout<<arrayname[k][l]; if(l=3) cout<<"\n"; } } errors: e:\semester 2\cprograms\array2.cpp in function `int main()': 10 e:\semester 2\cprograms\array2.cpp invalid conversion `int (*)[3][3]' `int' 10 e:\semester 2\cprograms\array2.cpp initializing argument 1 of `void f(int, int)' e:\semester 2\cprograms\array2.cpp in function `void f(int, int)': 22 e:\semester 2\cprograms\array2.cpp invalid types `int[int]' array subscript (last error repeated 5 times)
all done before us.:)
you can assignment using standard algorithm std::reverse
declared in header <algorithm>
for example
#include <iostream> #include <algorithm> #include <iterator> int main() { int a[3][3] = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } }; ( const auto &row : ) { ( int x : row ) std::cout << x << ' '; std::cout << std::endl; } std::cout << std::endl; std::reverse( std::begin( ), std::end( ) ); ( const auto &row : ) { ( int x : row ) std::cout << x << ' '; std::cout << std::endl; } return 0; }
the program output is
1 2 3 4 5 6 7 8 9 7 8 9 4 5 6 1 2 3
as code function declaration
void f(int arrayname, int size);
is wrong.
the first parameter should either reference array or pointer first element.
for example
void f( int ( &arrayname )[3][3] );
or
void f( int ( *arrayname )[3], int size );
if want write function can following way
#include <iostream> void reverse( int ( *arrayname )[3], size_t size ) { ( size_t = 0; < size / 2; i++ ) { ( size_t j = 0; j < 3; j++ ) { int tmp = arrayname[i][j]; arrayname[i][j] = arrayname[size - - 1][j]; arrayname[size - - 1][j] = tmp; } } } int main() { int a[3][3] = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } }; ( const auto &row : ) { ( int x : row ) std::cout << x << ' '; std::cout << std::endl; } std::cout << std::endl; ::reverse( a, 3 ); ( const auto &row : ) { ( int x : row ) std::cout << x << ' '; std::cout << std::endl; } return 0; }
the program output same above.
Comments
Post a Comment