簡體   English   中英

如何在C語言中將2D數組傳遞給函數

[英]How to pass 2D array into a function in C

我做了這個代碼:

int n,m;

void print(int a[][m])
{
int i=0,j=0;
    for(;i<n;i++)
    {
        for(j=0;j<m;j++)
            printf("%d ",a[i][j]);
        printf("\n");
    }
}

int main()
{
scanf("%d %d",&n,&m);
int a[100][100];
int i=0;
    int j=0;
    for(;i<n;i++)
    {
        for(j=0;j<m;j++)
            scanf("%d",&a[i][j]);
    }
    print(a);

return 0;
}

但是我無法回憶起所傳遞的完整2D數組。

如果我的輸入是

4 4
1 2 3 4
4 5 6 7
5 6 7 8
5 4 3 2

我得到的輸出

1 2 3 4
0 0 0 0
0 0 0 0
0 0 0 0

如何將完整的數組傳遞給函數?

您可以輸入值為4的m,但數組a的大小仍為100 因此,當您編寫scanf("%d",&a[i][j]); 對於i = 1 ,您正在讀取數組的第101個元素,這不是前16個元素的一部分。 你需要有a的尺寸m為了你盡力去做。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM