如何将数组传递给函数?指针?

时间:2011-03-24 06:10:39

标签: c arrays pointers

尝试自学如何将数组从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

只需要了解指针的工作原理并通过,这样我就可以继续工作了。

1 个答案:

答案 0 :(得分:4)

二维数组衰减到指向一维数组的指针(即(*)[])

所以,从 -

改变
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] = { {'-','-','-'},
                 {'-','-','-'},
                 {'-','-','-'}
               };

Check Results