gpt4 book ai didi

c - c中矩阵的重新分配

转载 作者:行者123 更新时间:2023-11-30 19:40:52 25 4
gpt4 key购买 nike

这可能是一个非常愚蠢的问题,但我无法理解它,也许你可以帮忙?

我的问题是重新分配矩阵,向其添加 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。

最佳答案

假设您最初有一个 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);
}

关于c - c中矩阵的重新分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34580344/

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