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

标签 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

只需要了解指针的工作方式和传递方式,这样我就可以继续我的工作。

最佳答案

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

所以,从 -

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

关于c - 如何将数组传递给函数?指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5415414/

相关文章:

pointers - 如果我想在 Rust 中安全地编码,我应该在不使用指针算法的情况下编码吗?

C++ UDP套接字以一定频率破坏数据包

c - 从函数更新指向 c 数组的指针

c - 如何让printf在循环中只运行一次

arrays - 有没有办法直接在堆上分配一个标准的 Rust 数组,完全跳过堆栈?

C++双指针多态性

c++ - 如何创建一个指向函数指针的指针?

c - 如何使用嵌入式 Mongoose 实现 SSL

java - 在 Java 中创建直方图

c - 尝试修改指向数组的指针时出现段错误