【发布时间】:2021-07-12 02:06:51
【问题描述】:
所以我尝试创建两个动态数组,一个用于保存参考点,另一个用于保存查询点,但我收到此错误: malloc(): 损坏的顶部大小 中止(核心转储) 我想创建 2 个宽度相同的二维数组,行大小无关紧要,但应该至少有一行。
double **createSyntheticReference(int rows, int columns)
{
int i,j;
// Dynamically allocate a 2D array
double **student = (double **)malloc(rows * sizeof(int *));
for ( i=0; i<rows; i++)
student[i] = (double *)malloc(columns * sizeof(int));
// load synthetic data
for(i=0; i<rows;i++) {
for(j=0; j<columns; j++) {
student[i][j] = rand()%100+1;
}
}
for(i=0; i<rows; i++) {
printf("%lf", student[i][0]);
for(j=1; j<columns; j++) {
printf("%17lf", student[i][j]);
}
puts("");
}
return student;
}
double **createSyntheticQuery(int columns)
{
int i,j;
int rows = 10;
// Dynamically allocate a 2D array
double **query = (double **)malloc(rows * sizeof(int *));
for ( i=0; i<rows; i++)
query[i] = (double *)malloc(columns * sizeof(int));
// load synthetic data
for(i=0; i<rows;i++) {
for(j=0; j<columns; j++) {
query[i][j] = rand()%100+1;
}
}
for(i=0; i<rows; i++) {
printf("%lf", query[i][0]);
for(j=1; j<columns; j++) {
printf("%17lf", query[i][j]);
}
puts("");
}
return query;
}
在我的主程序中,我运行它来尝试创建 2 个二维数组:
double **student = createSyntheticReference(rows, columns);
double **query = createSyntheticQuery(columns);
【问题讨论】:
-
double **student = (double **)malloc(rows * sizeof(int *));一侧有double,另一侧有int。你那里有什么闹钟吗?投射不是魔法 - 如果你强制将它投射到不正确的地方,你会得到不正确的结果。 -
@kaylum tx 没有意识到有时会犯愚蠢的错误;)它现在可以工作了
-
@Barmar 你喜欢什么?
-
double **student = malloc(rows * sizeof(*student));
标签: c multidimensional-array dynamic-arrays