C - 在函数中分配矩阵 [英] C - allocating a matrix in a function

查看:21
本文介绍了C - 在函数中分配矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用具有维度和三重指针的函数来分配矩阵.我已经分配了一个 int**(设置为 NULL)并且我将它的地址作为函数的参数传递.由于某种原因,这让我违反了内存访问.

I am trying to allocate a matrix using a function that takes its dimensions and a triple pointer. I have allocated an int** (set to NULL) and I am passing its address as the function's argument. That gives me a mem access violation for some reason.

void allocateMatrix(int ***matrix, int row, int col)
{
    int i;
    if((*matrix = (int**)malloc(row * sizeof(int*))) == NULL)
    {
        perror("There has been an error");
        exit(EXIT_FAILURE);
    }
    for(i = 0; i < row; ++i)
    {
        if((*matrix[i] = (int*)malloc(col * sizeof(int))) == NULL)
        {
            perror("There has been an error");
            exit(EXIT_FAILURE);
        }
    }
}

/* main.c */

    int** matrix = NULL;
    allocateMatrix(&matrix, MATRIX_ROW, MATRIX_COL); //error

推荐答案

你需要改变

if((*matrix[i] = (int*)malloc(col * sizeof(int))) == NULL)

if(((*matrix)[i] = (int*)malloc(col * sizeof(int))) == NULL)
//  ^       ^

在使用数组下标之前,您需要取消引用matrix.
*matrix[i] 等价于 *(matrix[i])

You need to dereference matrix before using the array subscript.
*matrix[i] is equivalent to *(matrix[i])

这篇关于C - 在函数中分配矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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