内C - 功能分配矩阵 [英] C - allocating a matrix in a function
本文介绍了内C - 功能分配矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想用一个函数,它的尺寸和三重指针分配矩阵。我分配了一个int **(设置为NULL),我通过它的地址作为函数的参数。这给了我一个纪念品访问冲突的某些原因。
无效allocateMatrix(INT ***矩阵,诠释行,诠释山口)
{
INT I;
如果((*矩阵=(INT **)的malloc(行*的sizeof(INT *)))== NULL)
{
PERROR(有错误);
出口(EXIT_FAILURE);
}
对于(i = 0; I<排; ++ I)
{
如果((*矩阵[I] =(INT *)malloc的(COL *的sizeof(int)的))== NULL)
{
PERROR(有错误);
出口(EXIT_FAILURE);
}
}
}/ * * main.c中/ INT **矩阵= NULL;
allocateMatrix(安培;矩阵,MATRIX_ROW,MATRIX_COL); //错误
解决方案
您需要修改
如果((*矩阵[I] =(INT *)malloc的(COL *的sizeof(int)的))== NULL)
到
如果(((*矩阵)[I] =(INT *)malloc的(COL *的sizeof(int)的))== NULL)
// ^^
您需要取消引用矩阵
使用数组下标前。
结果 *矩阵[I]
等同于 *(矩阵[I])
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
解决方案
You need to change
if((*matrix[i] = (int*)malloc(col * sizeof(int))) == NULL)
to
if(((*matrix)[i] = (int*)malloc(col * sizeof(int))) == NULL)
// ^ ^
You need to dereference matrix
before using the array subscript.
*matrix[i]
is equivalent to *(matrix[i])
这篇关于内C - 功能分配矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文