我尝试了以下方法来重新分配一个 2Dfloat
数组,其大小从 2X2 变为 3X3。代码会抛出一段segfault
时间试图realloc
记忆weights[2]
.
num_vertices = 2;
float **weights = malloc(num_vertices*sizeof(float *)); // weight array matrix
for(i = 0; i < num_vertices; i++){
weights[i] = malloc(num_vertices*sizeof(float));
}
num_vertices = 3;
weights = realloc(weights, num_vertices*sizeof(float *)); // weight array matrix
for(i = 0; i < num_vertices; i++){
weights[i] = realloc(weights[i], num_vertices*sizeof(float));
}
当然,我可以一次又一次地free
使用 2D 数组malloc
,但我一直在寻找更优雅的解决方案。有任何想法吗?