这可能是一个非常愚蠢的问题,但我看不清楚,也许你可以提供帮助?
我的问题是重新分配矩阵,向其中添加1列和1行,然后用“INFINITY”填充新元素。
#include <stdio.h>
#include <stdlib.h>
int main(){
int i, j, size = 3;
float **mat;
//Initial allocation
mat = malloc(size* sizeof(float *));
for(i = 0; i < size; i++) {
mat[i] = malloc(size * sizeof(float));
for (j = 0; j < size; j++)
mat[i][j] = 1;
}
//Print initial matrix
for(i=0; i<size; i++) {
for (j = 0; j < size; j++)
printf("%f ", mat[i][j]);
puts("\n");
}
//I'm going to add a row and a column
void *pointer = realloc(mat, (size+1)*sizeof(float*));
if(pointer != NULL) {
mat = pointer;
mat[size] = malloc((size+1)*sizeof(float));
}else
fprintf(stderr, "Error: allocation");
for(i = 0; i <= size; i++) {
mat[i][size] = 0;
mat[size][i] = 0;
}
//Print altered matrix
for(i=0; i<=size; i++) {
for (j = 0; j <= size; j++)
printf("%f ", mat[i][j]);
puts("\n");
}
//Here comes the free
for (i = 0; i < size+1; i++){
free(mat[i]); // <-- Debug says SIGTRAP
}
free(mat);
return 0;
}
提前感谢您的帮助。
编辑:我注意到只有在我调试它时才会出现错误,而不是在正常运行时。我的IDE是Clion。
答案 0 :(得分:0)
假设您最初拥有2x2阵列。
x x
x x
在调用realloc和malloc之后,您已经创建了一个如下所示的对象:
x x
x x
x x x
要解决此问题,您还需要在每一行上调用realloc。
完整的解决方案可能如下所示:
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
int main(){
int i, j, size = 3;
float **mat;
// Initial allocation
mat = malloc(size * sizeof(float *));
for(i = 0; i < size; i++)
mat[i] = malloc(size * sizeof(float));
// Initial values
for(i = 0; i < size; i++)
for (j = 0; j < size; j++)
mat[i][j] = 1;
// Print initial matrix
for(i = 0; i < size; i++) {
for (j = 0; j < size; j++)
printf("%f ", mat[i][j]);
printf("\n");
}
printf("\n");
// I'm going to add a row and a column
mat = realloc(mat, (size+1)*sizeof(float*));
for(i = 0; i < size; i++)
mat[i] = realloc(mat[i], (size+1)*sizeof(float));
mat[size] = malloc((size+1) * sizeof(float));
for(i = 0; i <= size; i++) {
mat[i][size] = 0;
mat[size][i] = 0;
}
//Print altered matrix
for(i = 0; i <= size; i++) {
for (j = 0; j <= size; j++)
printf("%f ", mat[i][j]);
printf("\n");
}
//Here comes the free
for (i = 0; i <= size; i++)
free(mat[i]);
free(mat);
}