我知道我正在將陣列拆分為雙指標,但是如果我丟失了資料軌道,我該如何解除分配?
#include <stdio.h>
#include <stdlib.h>
#define width 20
#define height 20
void allocate_matrix(int ***matrix)
{
double **local_matrix, *data;
local_matrix = (double **)malloc(sizeof(double *) * height);
data = (double *)malloc(sizeof(double) * width * height);
for (int i = 0; i < height; i )
{
local_matrix[i] = &(data[i * width]);
}
*matrix = local_matrix;
}
void deallocate_matrix(int **matrix) {
}
int main(void) {
int **matrix;
allocate_matrix(&matrix);
deallocate_matrix(matrix);
return 0;
}
uj5u.com熱心網友回復:
你沒有忘記第二個指標。如果你看看你的回圈體:
local_matrix[i] = &(data[i * width]);
當i為0時,local_matrix[0]被分配&data[0]該相同data。所以這就是你需要釋放的:
void deallocate_matrix(int **matrix) {
free(matrix[0]);
free(matrix);
}
uj5u.com熱心網友回復:
首先,您正在分配空間,double然后將其用作int,這沒有意義(并且不會編譯)。
但這里的主要問題是您不應將其分配為碎片段,而是將其分配為連續的 2D 陣列。請學習正確分配多維陣列。這將大大提高性能,并且可能(可以說)使代碼更易于閱讀。
如果我們遵循該帖子中的建議,那么您的代碼可以重寫為:
#include <stdio.h>
#include <stdlib.h>
void allocate_matrix(size_t height, size_t width, int (**matrix)[height][width])
{
int (*local_matrix) [height][width];
local_matrix = malloc(sizeof *local_matrix);
if(local_matrix == NULL)
{
// handle errors
}
*matrix = local_matrix;
}
int main (void)
{
const size_t height = 20;
const size_t width = 20;
int (*matrix)[height][width];
allocate_matrix(height, width, &matrix);
int(*pmatrix)[width] = *matrix; // pointer to first 1D array for easier syntax
for(size_t h=0; h<height; h )
{
for(size_t w=0; w<width; w )
{
pmatrix[h][w] = h w; // assign some sort of data
printf("%d ", pmatrix[h][w]);
}
printf("\n");
}
free(matrix);
return 0;
}
正如你所看到的,這也消除了對復雜的釋放例程的需要,因為我們可以直接將指標傳遞給free()一個地方并釋放所有的東西。
uj5u.com熱心網友回復:
以下建議代碼:
- 需要頭檔案:
stdlib.hexit() 和 malloc() 和 EXIT_FAILURE 的原型 - 執行所需的功能
- 您可能想要修改矩陣的初始化值的計算
現在,建議的代碼:
double **allocate_matrix(void)
{
local_matrix** = malloc( sizeof(double *) * height );
if( ! local_matrix )
{
perror( "malloc for matrix height failed:");
exit( EXIT_FAILURE );
}
for( size_t y = 0; y<height; y )
{
local_matrix[y] = malloc( sizeof(double) * width );
if( !local_matrix[y] )
{
//cleanup and exit
}
for ( size_t i = 0; i < width; i )
{
local_matrix[y][i] = i;
}
}
return local_matrix;
}
int main( void )
{
double **matrix;
matrix = allocate_matrix();
for( size_t y= 0; y< height; y )
{
free( matrix[ y ] ):
}
free( matrix );
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/369512.html
上一篇:與printf(c)中的解釋相同
