如何将2D动态分配的数组传递给函数? [英] How to pass a 2D dynamically allocated array to a function?

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

问题描述

我在函数main中的C代码中动态分配了一个二维数组.我需要将此2D数组传递给函数.由于数组的列和行是运行时变量,所以我知道传递它的一种方法是:

I have a 2 dimensional array dynamically allocated in my C code, in my function main. I need to pass this 2D array to a function. Since the columns and rows of the array are run time variables, I know that one way to pass it is :

-将行和列变量以及指针传递给数组的[0] [0]元素

-Pass the rows and column variables and the pointer to that [0][0] element of the array

myfunc(&arr[0][0],rows,cols)

然后在所调用的函数中,将其作为展平"的一维数组进行访问,例如:

then in the called function, access it as a 'flattened out' 1D array like:

ptr[i*cols+j]

但是我不想那样做,因为那将意味着代码的大量更改,因为从前,传递给该函数的2D数组是静态分配的,其尺寸在编译时就知道了.

But I don't want to do it that way, because that would mean a lot of change in code, since earlier, the 2D array passed to this function was statically allocated with its dimensions known at compile time.

那么,如何将2D数组传递给函数,并且仍然能够将其用作具有2个索引的2D数组,如下所示?

So, how can I pass a 2D array to a function and still be able to use it as a 2D array with 2 indexes like the following?

arr[i][j].

任何帮助将不胜感激.

推荐答案

请参见下面的代码.将2d数组的基本位置作为双指针传递到myfunc()之后,您可以使用s[i][j]按索引访问数组中的任何特定元素.

See the code below. After passing the 2d array base location as a double pointer to myfunc(), you can then access any particular element in the array by index, with s[i][j].

#include <stdio.h>
#include <stdlib.h>

void myfunc(int ** s, int row, int col) 
{
    for(int i=0; i<row; i++) {
        for(int j=0; j<col; j++)
            printf("%d ", s[i][j]);
        printf("\n");
    }
}

int main(void)
{
    int row=10, col=10;
    int ** c = (int**)malloc(sizeof(int*)*row);
    for(int i=0; i<row; i++)
        *(c+i) = (int*)malloc(sizeof(int)*col);
    for(int i=0; i<row; i++)
        for(int j=0; j<col; j++)
            c[i][j]=i*j;
    myfunc(c,row,col);
    for (i=0; i<row; i++) {
        free(c[i]);
    }
    free(c);
    return 0;
}

这篇关于如何将2D动态分配的数组传递给函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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