将2D数组传递给C的方法 [英] Ways to pass 2D Array to function in C

查看:59
本文介绍了将2D数组传递给C的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一周前开始学习C语言. 为了测试,我决定写一个tictactoe游戏.

I started learning C language a week ago. Just for the test I decided to write a tictactoe game.

我有一个字段.

int field[3][3];

还有一个函数printField

And a function printField

void printField(int field[3][3]){
for(int i = 0; i < 3; i++){
    for(int j = 0; j < 3; j++){
        printf("%i", field[i][j]);
    }
    printf("\n");
}}

它主要在这样工作:

int main(){
printField(field);}

但如果我更改

 void printField(int field){...}

void printField(int field[][]){...}

这给了我很多错误:

subscripted value is neither array nor pointer nor vector                      
passing argument 1 of ‘printField’ makes integer from pointer without a cast
note: expected ‘int’ but argument is of type ‘int (*)[3]’

为什么我不能像这样传递数组? 还有其他方法可以通过吗?

Why can't I pass the array like this? Are there any more ways to pass it?

推荐答案

该函数独立于对该函数的任何调用.因此,该函数无法从程序的其余部分猜测数组的大小.在函数主体中,必须具有常量或变量才能表示所有尺寸.

The function is independent of any call to the function. So the function cannot guess from the rest of the program what the array size is. In the function body you have to have constants or variables to represent all dimensions.

您可以为此使用变量而不是固定大小:

You can use variables for this instead of fixed size:

void printField(int r, int c, int field[r][c])
{
    for(int i = 0; i < r; i++)
        for(int j = 0; j < c; j++)
            printf("%i", field[i][j]);

    printf("\n");
}

并调用该函数:

printField(3, 3, field);

您可以根据数组的名称计算尺寸.使用宏限制了丑陋的语法:

You can compute the dimensions from the array's name. Using a macro confines the ugly syntax:

#define printField(a) printField( sizeof(a)/sizeof((a)[0]), sizeof((a)[0]) / sizeof((a)[0][0]), (a) )

int f1[3][3] = { 0 };
printField(f1);

int f2[4][5] = { 0 };
printField(f2);

这篇关于将2D数组传递给C的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆