簡體   English   中英

如果我不知道尺寸,將二維數組傳遞給函數

[英]Passing a 2d array to a function if I don't know the dimensions

我正在嘗試編寫一個C函數來添加兩個數組。 該函數應適用於任何數組大小,並且應接收對數組以及行數和列數的引用,並且應返回指向結果數組第一個元素的指針。 我該怎么做? 當我嘗試將二維數組傳遞給函數時,出現錯誤?

#include<stdio.h>
void function(int r, int c,int a[][]){
    int i,j;
    for(i=0;i<r;i++)
    {
        for(j=0;j<c;j++)
        {
            printf("%d, ",a[i][j]);
        }
        printf("\n");
    }

 }

int main(){
    int array[2][2] = {{1,2},{4,5}};
    function(2,2,array);

    return 0;
}

假設C99或C11具有未定義__STDC_NO_VLA__的實現,則可以使用可變長度數組(VLA)表示法並可以編寫:

void function(int r, int c, int a[r][c])
{
    for (int i = 0; i < r; i++)
    {
        for (int j = 0; j < c; j++)
            printf("%d, ", a[i][j]);
        putchar('\n');
    }
}

或等效的東西。 在數組規范中使用尺寸之前,必須先定義尺寸。

如果您甚至無法訪問C99編譯器,而僅訪問C90編譯器,則必須將指針傳遞給數組的第一個元素和大小,然后顯式執行數組索引計算。

void function(int r, int c, int *a)
{
    for (int i = 0; i < r; i++)
    {
        for (int j = 0; j < c; j++)
            printf("%d, ", a[i * c + j]);
        putchar('\n');
    }
}

現在,您可以像下面這樣調用函數:

int main(void)
{
    int array[2][2] = { { 1, 2 }, { 4, 5 } };
    function(2, 2, &array[0][0]);
    return 0;
}

暫無
暫無

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

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