gpt4 book ai didi

c - 释放C中的三重指针

转载 作者:太空宇宙 更新时间:2023-11-04 07:01:13 24 4
gpt4 key购买 nike

<分区>

首先,我创建了一个 int** 并成功地(我认为)释放了它,如下所示:

for (int i = 0; i < r; i++) 
free(A[i]);
free(A);

然后我创建了一个 int*** 并尝试使用相同的逻辑释放它:

for (int i = 0; i < n_rows; i++) {
for (int j = 0; i < n_cols; j++) {
free(matrix[i][j]);
}
free(matrix[i]);
}
free(matrix);

但是我得到了错误:

pointer being freed was not allocated

我哪里错了?我试图让这篇文章简短,但如果包括我如何创建 int*** 很重要,我可以添加它。

编辑,完整代码:

// Uninitialized 3D matrix
int*** malloc3Dmatrix(int n_rows, int n_cols, int depth) {
int ***matrix;
matrix = malloc(n_rows*sizeof(int**));
for (int row = 0; row < n_rows; row++) {
matrix[row] = malloc(n_cols*sizeof(int*));
for (int col = 0; col < n_cols; col++) {
matrix[row][col] = malloc(depth*sizeof(int));
}
}
return matrix;
}

// fill 3D matrix
void fill3DMatrix(int ***matrix, int n_rows, int n_cols, int depth) {

printf("Insert the elements of your matrix:\n");
for (int i = 0; i < n_rows; i++) {
for (int j = 0; j < n_cols; j++) {
for (int k = 0; k < depth; k++) {
printf("Insert element [%d][%d][%d]: ", i, j, k);
scanf("%d", &matrix[i][j][k]);
printf("matrix[%d][%d][%d]: %d\n", i, j, k, matrix[i][j][k]);
}
}
}
return;
}

int main(){

// create uninitialized 3D matrix
int n_rows = 3, n_cols = 3, depth = 3;
int ***matrix = malloc3Dmatrix(n_rows, n_cols, depth);

// fill and print 3D matrix
fill3DMatrix(matrix, n_rows, n_cols, depth);
print3DMatrix(matrix, n_rows, n_cols, depth);


// free 3D matrix
for (int i = 0; i < n_rows; i++) {
for (int j = 0; i < n_cols; j++){
free(matrix[i][j]);
}
free(matrix[i]);
}
free(matrix);


return 0;
}

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com