gpt4 book ai didi

c - Malloc 与 3 星 ptr

转载 作者:行者123 更新时间:2023-11-30 19:13:38 28 4
gpt4 key购买 nike

void alloc (int*** matr, int r, int c)
{
int i, j;
*matr=malloc(r*sizeof(***matr));
for (i=0; i<r; i++)
*matr[i]=malloc(c*sizeof(**matr));

for (i=0; i<r; i++)
for (j=0; j<c; j++)
*matr[i][j]=12;
}

老师给出的函数原型(prototype)。我收到的错误是段错误。谢谢各位的解答!

最佳答案

假设matr已初始化,则语句

*matr=malloc(r*sizeof(***matr)); // ***matr is of "int" type   

应该是

*matr = malloc(r*sizeof(int *));   // Allocate an array of "r" int *
//matr[0] = malloc(r*sizeof(int *));

for循环中,语句

*matr[i]=malloc(c*sizeof(**matr));  // **mtr is of "int *" type

应该是

(*matr)[i] = malloc(c*sizeof(int)); // Allocate an array of "c" int
//matr[0][i] = malloc(c*sizeof(int));

然后将 *matr[i][j]=12; 更改为 (*matr)[i][j]=12;matr [0][i][j]=12;

查看工作代码示例:https://ideone.com/hboLKV

关于c - Malloc 与 3 星 ptr,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35322833/

28 4 0
文章推荐: javascript - p5js for 循环编程 Q : how to make circles bigger and brighter near mouse pointer
文章推荐: c# - 如何将 List 传递给 WCF