【问题标题】:Dynamic allocation for 2 2D arrays in CC中2个二维数组的动态分配
【发布时间】:2021-07-12 02:06:51
【问题描述】:

所以我尝试创建两个动态数组,一个用于保存参考点,另一个用于保存查询点,但我收到此错误: ma​​lloc(): 损坏的顶部大小 中止(核心转储) 我想创建 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


【解决方案1】:

@kaylum 帮我解决了问题,我没有看到我为 int 分配空间,但它应该是双倍的

double **student = (double **)malloc(rows * sizeof(double *)); 
    for ( i=0; i<rows; i++) 
         student[i] = (double *)malloc(columns * sizeof(double));

【讨论】:

  • 你可以通过引用变量而不是类型来避免这个问题:rows * sizeof(*student)columns * sizeof(*student[i])
猜你喜欢
  • 2021-02-03
  • 2015-09-17
  • 1970-01-01
  • 1970-01-01
  • 2015-02-10
  • 2013-11-14
  • 2017-09-28
  • 2017-03-11
相关资源
最近更新 更多