传递二维数组以在 C 中运行 [英] Passing a 2D array to function in C

查看:41
本文介绍了传递二维数组以在 C 中运行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个二维数组(一个棋盘,但这与问题无关),我想用一个函数来填充它.我写的那个工作正常,但是在启动程序后控制台崩溃了.知道问题出在哪里吗?谢谢.

I have a 2d array (a chess board, but this is irrelevant to the problem) and I want to fill it using a function. The one I've written works fine, but after launching the program the console crashes. Any idea where the problem is? Thank you.

#include <stdio.h>
#include <stdlib.h>
void fill(int board[8][8]);
int main()
{   int board[8][8];
    fill(board);
    return 0;
}
void fill(int board[8][8])
{
    int a,b;

    for (a = 1; a <= 8; a++)
    {
        for (b = 1; b<= 8; b++)
        {
            if ((a==1) || (a==8)) board[a][b] = 7;
            if ((a==2) || (a==7)) board[a][b] = 9;
            if ((a==3) || (a==6)) board[a][b] = 11;
            if ((a==4) || (a==5)) board[a][b] = 13;
            printf("%d", board[a][b]);
        }
        printf("\n");
    }
}

推荐答案

我看到一个问题:数组在 C 中从 0 开始索引.所以最后一种情况是 board[7][7].

I see one problem: arrays are indexed from 0 in C. So the last case is board[7][7].

访问board[8][0] 实际上访问的是实际数组结束后的子数组(行).如果数组后面的内存不属于您的程序(著名的分段错误),它将编译但会崩溃.

Accessing board[8][0] actually accesses the sub-array (the row) after the end of the actual array. It will compile but crash if the memory after the array isn't owned by your program (the famous segmentation fault).

我想你应该把 a-1b-1 放在方括号之间.

I guess you should put a-1 and b-1 between the square brackets.

这篇关于传递二维数组以在 C 中运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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