我试图填充和打印2d数组,但每次我试图编译它表示未声明的标识符c。并将箭头指向print函数中的c。我尝试了很多方法来声明它,但由于某种原因,它不工作。
#include <iostream>
using namespace std;
void print(char x[][c], int r)
{
for(int r = 0; r < 25; r++)
{
for(int c = 0; c < 25; c++)
{
cout << x[r][c];
}
cout << endl;
}
}
int main()
{
void print(char x[][c], int r);
char p[25][25];
for(int r = 0; r < 25; r++)
{
for(int c = 0; c < 25; c++)
{
if(r==0)p[r][c]='x';
else p[r][c]='o';
}
}
print(p[25][25]);
return(0);
}
这样写
#include <iostream>
using namespace std;
const size_t ROWS = 25;
const size_t COLS = 25;
void print(char x[][COLS], size_t r )
{
for ( size_t i = 0; i < r; i++ )
{
for ( size_t j = 0; j < COLS; j++ )
{
cout << x[i][j];
}
cout << endl;
}
}
int main()
{
char p[ROWS][COLS];
for ( size_t i = 0; i < ROWS; i++ )
{
for ( size_t j = 0; j < COLS; j++ )
{
if ( i == 0 ) p[i][j] = 'x';
else p[i][j] = 'o';
}
}
print( p, ROWS );
return(0);
}
另一种方法是按以下方式定义函数
void print( char ( &x )[ROWS][COLS] )
{
for ( size_t i = 0; i < ROWS; i++ )
{
for ( size_t j = 0; j < COLS; j++ )
{
cout << x[i][j];
}
cout << endl;
}
}
并将其命名为
print( p );
试试这个:
#include <iostream>
using namespace std;
void print(char x[25][25])
{
for(int r = 0; r < 25; r++)
{
for(int c = 0; c < 25; c++)
{
cout << x[r][c];
}
cout << endl;
}
}
int main()
{
char p[25][25];
for(int r = 0; r < 25; r++)
{
for(int c = 0; c < 25; c++)
{
if(r==0)p[r][c]='x';
else p[r][c]='o';
}
}
print(p);
return(0);
}