将三重指针传递给函数,然后分配2d数组 [英] passing a triple pointer into function then mallocing a 2d array
问题描述
遇到分段错误并且不明白为什么,必须传递三重指针进行赋值,这样就无法更改...
Getting a segmentation fault and don't understand why, have to pass in triple pointer for assignment so can't change that...
这是功能
void alloc2d(double*** a, int m, int n) {
int i, j;
**a = malloc(sizeof(double *) * m);
a[0] = malloc(sizeof(double) * n * m);
for(i = 0; i < m; i++)
a[i] = (*a + n * i);
}
这里是函数的调用...
Here's the calling of the function...
double** m;
alloc2d(&m, 5, 10);
double count = 0.0;
for (int i = 0; i < 5; i++)
for (int j = 0; j < 10; j++)
m[i][j] = ++count;
for (int i = 0; i < 5; i++)
for (int j = 0; j < 10; j++)
printf("%f ", m[i][j]);
推荐答案
您要为a
所指向的指针分配内存.将**a = malloc(sizeof(double *) * m);
更改为*a = malloc(sizeof(double *) * m);
.您已经为a[0]
分配了内存,因此从索引1
开始循环.与*a
相似的a[0]
类型为double**
,但是您想要设置a[0]
所指向的指针.将a[0]
更改为(*a)[0]
,将a[i]
更改为(*a)[i]
.像这样修改您的代码:
You want to allocate the the memory for the pointer where a
refers to. Change **a = malloc(sizeof(double *) * m);
to *a = malloc(sizeof(double *) * m);
. You alraedy allocated the memory for a[0]
, so start your loop with index 1
. The type of a[0]
which is similar to *a
is double**
, but you want to set the pointer where a[0]
refers to. Change a[0]
to (*a)[0]
and a[i]
to (*a)[i]
. Adapt your code like this:
void alloc2d(double*** a, int m, int n) {
*a = malloc( sizeof( double* ) * m ); // allocate the memory for (m) double*
(*a)[0] = malloc( sizeof(double) * n * m ); // allocate the linearized memory for (n*m) double
for( int i=1; i<m; i++ )
(*a)[i] = (*a)[0] + n*i; // initialize the pointers for rows [1, m[
}
我认为这会更容易理解:
I think this would be more comprehensible:
void alloc2d(double*** a, int m, int n) {
double **temp = malloc( sizeof( double* ) * m ); // allocate the memory for (m) double*
temp[0] = malloc( sizeof(double) * n * m ); // allocate the linearized memory for (n*m) double
for ( int i=1; i<m; i++ )
temp[i] = temp[0] + n*i; // initialize the pointers for rows [1, m[
*a = temp; // assign dynamic memory pointer to output parameter
}
这篇关于将三重指针传递给函数,然后分配2d数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!