c - 在 C 函数中为二维数组分配空间?

标签 c arrays function matrix malloc

我正在用 C 语言解决一些计算物理问题,我对我的代码有些困惑。过去几周我一直在阅读有关 C 的内容,但我对这门语言还是陌生的。

我需要处理一个二维数组。每行的长度可能会有所不同,例如,我可能想使用:创建和修改“三角形”矩阵:[[0,1,2][1,2][2]].

为了以可维护、易于阅读和修改的方式构建我的代码,我想将部分逻辑移动到一个函数中。然而,这似乎比我预期的要难。

我从一种方法开始,我创建了一个 int **matrix 变量并将它传递给一个函数,并在它前面加上 ampersand 前缀。并接受一个三星级的 int:int ***,并使用矩阵作为 *matrix[i][j]。我无法让它工作,但是 matrix[0][i][j] 工作了,我只是无法理解它。这两个概念不是一样的吗?

这是我的代码:

void alloc_subscript_notation(int number_of_rows, int *** matrix) {
    matrix[0] = malloc(number_of_rows * sizeof(int *));
    for (int i = 0; i < number_of_rows; i++)
        matrix[0][i] = calloc((number_of_rows-i), sizeof(int));

}

void modify_subscript(int number_of_rows, int *** matrix) {
    matrix[0][0][1] = 8;  // just set a value of an element to 8, as a proof of concept
}

void subscript_notation (int number_of_rows, int *** matrix) {
    alloc_subscript_notation(number_of_rows, matrix);
    modify_subscript(number_of_rows, matrix);  // I can even modify it
}


void alloc_star_notation(int number_of_rows, int *** matrix) {
    *matrix = malloc(number_of_rows * sizeof(int *));

    for (int i = 0; i < number_of_rows; i++)
        *matrix[i] = calloc((number_of_rows-i), sizeof(int));

    printf("alloc_subscript_notation: zeros: %d, %d, %d\n",  // just a few examples
           *matrix[0][2], *matrix[1][1], *matrix[2][0]);
}

void star_notation (int number_of_rows, int *** matrix) {
    // SEGMENTATION FAULT!!!
    alloc_star_notation(number_of_rows, matrix);
}

int main (void) {
    int ** matrix;
    int number_of_rows = 3;  // it's dynamic in my program, but I use it this hard-coded value for clarity
    // I want to be able to access matrix elements here
    // All good here.
    subscript_notation(number_of_rows, &matrix);
    printf("subscript_notation ready. main: "
           " %d, %d, %d, modified: %d\n",
           matrix[0][2], matrix[1][1], matrix[2][0], matrix[0][1]);

    // Segmentation Fault
    star_notation(number_of_rows, &matrix);
}

最佳答案

不,*matrix[i][j]matrix[0][i][j] 不一样。

前者等同于*(matrix[i][j]),而后者等同于(*matrix)[i][j]

由于您正在尝试使用地址运算符访问传递给函数的指针,因此您必须使用后一个版本。

关于c - 在 C 函数中为二维数组分配空间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40377415/

相关文章:

javascript - 为什么我的过滤器没有按预期工作?

c++ - 你能从 LLVM pass 调用 pass 吗?

javascript - 如果存在则推送到 javascript 数组,如果不存在则先创建它

javascript - 数组元素在控制台日志中正确,但渲染不正确

c# - 为什么创建新数组会抛出 OutOfMemoryException?

java - 能够从不同的类访问文本区域

JavaScript Chrome 扩展 : Function is not defined

c - 检测C中的空行

c++ - 单程搜索和替换

c - 二值图像的简单多 Blob 检测?