我有以下代码用于在运行时分配浮点矩阵:
float **create_matrix(int w, int h) {
// alocates the matrix rows first
float **matrix = (float**)malloc(h * sizeof(float*));
// now allocates and populates each line
for (int i = 0; i < h; i++) {
matrix[i] = (float*) malloc(w * sizeof(float));
// sample matrix filling
for (int j = 0; j < w; j++)
matrix[i][j] = (i + 1) * (j + 1);
}
return matrix;
}
它似乎工作得很好,因为它不会崩溃,当我显示矩阵时,我有相同的值,我初始化它。尽管当我尝试释放矩阵时,如果行数小于列数,我收到以下错误消息:
a.out(14284,0x7fff73cc9300) malloc: * error for object 0x9000000000000000:被释放的指针没有被分配*在malloc_error_break中设置断点进行调试。流产陷阱:6"
释放例程如下:
void free_matrix(float **matrix, int h) {
for (int i = 0; i < h; i++)
free(matrix[i]);
free(matrix);
}
试试这个
#include <stdio.h>
#include <stdlib.h>
float **create_matrix(int h, int w)
{
float **matrix = (float **)malloc(h*sizeof(float *));
int i,j;
for(i=0;i<h;i++){
matrix[i] = (float *)malloc(w*sizeof(float));
}
for(i=0;i<h;i++){
for(j=0;j<w;j++){
matrix[i][j] = (i+1)*(j+1);
}
}
return matrix;
}
int main()
{
int h = 2, w = 3;
float **matrix = create_matrix(h,w);
int i,j;
for(i=0;i<h;i++){
for(j=0;j<w;j++){
printf("%.2f ",matrix[i][j]);
}
printf("n");
}
return 0;
}
您需要在开始操作之前分配内存