为什么我得到realloc()无效的旧大小?

时间:2019-06-11 15:16:40

标签: c++ dynamic-memory-allocation

我正在尝试管理4D动态分配的数组。 else语句中的代码给我错误。如果我不包含else语句,则代码正确,但这是一个好习惯吗?

int**** datind = (int****) malloc(nRow * sizeof(int***));
for (size_t i = 0; i < nRow; i++) {
    datind[i] = (int***) malloc(nCol * sizeof(int**));
}
for (size_t i = 0; i < nCol; i++) {
    for (size_t j = 0; j < nRow; j++) {
        datind[j][i] = (int**) malloc(1 * sizeof(int*));
    }
}

while ( fscanf(fp1, "%d %*c %d %*c %zu", &row, &col, &n_value) != EOF ) {
    if (n_value > 0) {
       datind[row-1][col-1] = (int**) realloc(datind[row-1][col-1], n_value * sizeof(int*));
       for (size_t i = 0; i < n_value; i++) {
           datind[row-1][col-1][i] = (int*) realloc(datind[row-1][col-1][i], 6 * sizeof(int));
           for (size_t j = 0; j < 6; j++) {
               fscanf(fp1,"%d%*c", &datind[row-1][col-1][i][j] );
           }
    } else {
       datind[row-1][col-1][0] = (int*) realloc(datind[row-1][col-1][0], 1 * sizeof(int));
       datind[row-1][col-1][0][0] = -1;
    }
}

用于3D数组的类似代码(即以int ***开头)可以很好地工作。

1 个答案:

答案 0 :(得分:0)

已解决!好的,这可行。我在注释中添加了提示,以提高代码质量。无需检查row和col是否等于0,因为我知道它们可以从1升至197。谢谢。

int **datind[(2*nx-1)][(2*ny-1)];

while ( fscanf(fp1, "%d %*c %d %*c %zu", &row, &col, &n_value) != EOF ) {

    if (n_value > 0) {

        datind[row-1][col-1] = (int**) malloc(n_value * sizeof(*datind));
        if (datind[row-1][col-1] == NULL) {
            printf("Memory allocation failed.\n");
            return EXIT_FAILURE;
        }

        for (size_t i = 0; i < n_value; i++) {
            datind[row-1][col-1][i] = (int*) malloc(6 * sizeof(*datind[row-1][col-1]));
            if (datind[row-1][col-1][i] == NULL) {
                printf("Memory allocation failed.\n");
                return EXIT_FAILURE;
            }

            for (size_t j = 0; j < 6; j++) {
                fscanf(fp1,"%d%*c", &datind[row-1][col-1][i][j] );
            }

        }
    } else {
        datind[row-1][col-1] = NULL;
    }

}