传递一个二维数组在C函数 [英] Passing a 2D array to a function in C

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

问题描述

我有,从本质上讲,数据矩阵(可以说整数),我想在一个二维数组中的维度不知道,直到运行时(比如x列和y行)来存储。我想填充功能的阵列,所以我想我需要做的是这样的:

I have, essentially, a matrix of data (lets say ints) that I would like to store in a 2D array in which the dimensions are not known until runtime (say x columns and y rows). I want to populate the array in a function, so I assume I need to do something like this:

int main(int argc, char **argv) {
    int y = atoi(argv[1]);
    int x = atoi(argv[2]);
    int **matrix = malloc(x * sizeof(int*));
    populateMatrix(matrix, y, x);
    return 0;
}

void populateMatrix(**matrix, int y, int x) {
    int i, j;
    for (i = 0; i < y; i++) {
        for (j = 0; j < x; j++) {
            matrix[i][j] = i * j; // populated with trivial data to keep it simple
        }
    }
}

显然,这并不工作,但我不知道怎么做,我准确描述。

Obviously this doesn't work, but I'm not sure how to do what I'm describing exactly.

推荐答案

什么你错过的是,每个内部阵列时也须malloc分配。

What you're missing is that each of the inner arrays needs to be malloc'ed too.

int **matrix = malloc(x * sizeof(int *));

应该是这样的:

int **matrix = (int **)malloc(y * sizeof(int *));
for (i = 0; i < y; ++i) {
    matrix[i] = (int *)malloc(x * sizeof(int));
}

这就是说,大多数矩阵库我所知道的只是将使用:

That said, most matrix libraries I'm aware of would just use:

int *matrix = (int *)malloc(x * y * sizeof(int));

然后使用:

int n = matrix[y * cols + x];

读取单个元素。对于(非稀疏)矩阵,这是不是让每一行单独分配的块比较有效。这也保证了数据的连续内存,可以使CPU的缓存更有效。

to read the individual elements. For (non-sparse) matrices this is more efficent than having a separately allocated block for each row. It also guarantees that the data is contiguous in memory which can make CPU caches more effective.

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

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