试图自学如何将数组从 int main()
传递给函数,但我就是不明白。
这是我的代码。
#include <stdio.h>
void printboard( char *B ) {
/*Purpose: to print out the tic tac toe board B
*/
int i,j;
printf("\n");
for (i=0;i<3;i++) {
for (j=0;j<3;j++) {
printf( " %c ",B[i][j]);
}
printf("\n\n");
}
}
int main( void ) {
char B[3][3] = { '-','-','-',
'-','-','-',
'-','-','-' };
printboard(B);
}
我收到这个错误:
test.c: In function 'printboard':
test.c:12: error: subscripted value is neither array nor pointer
test.c: In function 'main':
test.c:25: warning: passing argument 1 of 'printboard' from incompatible pointer type
只需要了解指针的工作方式和传递方式,这样我就可以继续我的工作。
最佳答案
二维数组衰减为指向一维数组的指针(即 (*)[] )
所以,从 -
void printboard( char *B )
{
// ....
}
到
void printboard( char B[][3] )
// Compiler is not bothered about first index because it
// converts to (*)[3]. So, is the reason it left empty.
{
// ...
}
还有,二维数组的初始化应该是这样的——
char B[3][3] = { {'-','-','-'},
{'-','-','-'},
{'-','-','-'}
};
关于c - 如何将数组传递给函数?指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5415414/