Calloc分配不一致

时间:2019-04-13 16:01:21

标签: c memory calloc

我正在使用指针和calloc函数创建2d整数数组。问题是我分配了一个3x5的矩阵。实际上,有3行但有6列。我无法理解这种行为。有人知道我在做什么错吗?

int main() {


int **new_lib = (int **) calloc(3, sizeof(int *));

if (new_lib == NULL) {
    fprintf(stderr, "Error: out of memory (create_library() part 1)\n");
    exit(1);
}

for (int i = 0; i < 3; ++i) {
    new_lib[i] = (int *) calloc(5, sizeof(int));

    if (new_lib[i] == NULL) {

        fprintf(stderr, "Error: out of memory (create_library() part 2)\n");
        exit(1);
    }
}

for (int i = 0; i < 3; ++i) {
    for (int j = 0; j < 6; ++j) {
        new_lib[i][j] = j * (i + 1) + i * (j + 1);
    }

}

for (int i = 0; i < 3; ++i) {
    for (int j = 0; j < 6; ++j) {
        printf("[%i][%i] = %i ", i, j, new_lib[i][j]);
    }
    printf("\n");
}
}

打印的内容对于另外一列是正确的:
[0][0] = 0 [0][1] = 1 [0][2] = 2 [0][3] = 3 [0][4] = 4 [0][5] = 5 [1][0] = 1 [1][1] = 4 [1][2] = 7 [1][3] = 10 [1][4] = 13 [1][5] = 16 [2][0] = 2 [2][1] = 7 [2][2] = 12 [2][3] = 17 [2][4] = 22 [2][5] = 27

1 个答案:

答案 0 :(得分:2)

它始终是一致的。在这里,您有一些更通用的。没有分配错误检查可以提高代码的可读性。

void *allocate(size_t selem, size_t rows, size_t cols)
{
    void **array = calloc(rows, sizeof(void *));

    for(size_t row =0; row < rows; row++)
    {
        array[row] = calloc(cols, selem);
    }
    return array;
}


int main()
{
    int **array = allocate(sizeof(int), 3, 5);

    for(size_t r = 0; r < 3; r++)
    {
        printf("%p\n",array[r]);   
    }

    for(size_t r = 0; r < 3; r++)
    {
        for(size_t c = 0; c < 5; c++)
        {
            array[r][c] = r*10 + c;   
        }
    }
    for(size_t r = 0; r < 3; r++)
    {
        for(size_t c = 0; c < 5; c++)
        {
            printf("%02d ", array[r][c]);   
        }
        printf("\n");
    }
}

https://onlinegdb.com/Hko5Wjy5V

编辑

您可以使用其他类型。只需传递正确的大小并分配正确的指针类型

typedef struct
{
    double  x[1000];
    int y[500]
    /* more stuff */
}MYSTRUCT;

int main()
{
    MYSTRUCT *ptr = allocate(sizeof(MYSTRUCT), 10, 50);
相关问题