我想使用free()從內存中刪除整個矩陣數組。我該怎麼做?free()C中的2D數組使用malloc
分配數組:
// test.h
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#define BYTE unsigned char
#define my_array(n_height, n_width) (BYTE **)create_array(sizeof(BYTE), (n_height), (n_width))
char **create_array(int u_size, int height, int width);
char **create_array(int u_size, int height, int width)
{
char **array;
int i;
if (!(array=(char **)malloc(height*sizeof(char *)))) {
printf("Memory allocation error.\n");
exit(0);
}
if (!(array[0]=(char *)malloc(height*width*u_size))) {
printf("Memory allocation error.\n");
exit(0);
}
for (i=1; i<height; i++)
array[i] = array[i-1] + width*u_size;
return array;
}
// test.c
#include "array.h"
int main()
{
unsigned char *bytes;
BYTE **matrix;
matrix = my_array(height, width);
int c = 0;
for (int h=0; h < height; h++) {
for (int w=0; w < (width); w++) {
matrix[h][w] = bytes[c];
c++;
}
}
printf("Done.\n");
free(matrix); // really empty memory??
}
我不能肯定是否基質已完全從當我使用免費的(矩陣)的存儲器中移除;
free(matrix [0]); free(matrix); 應該工作還是不工作? – wowofe
@wowofe wowofe:是的。 – caf
@unwind&caf:謝謝! – wowofe