首页 > 解决方案 > 有没有更好的解决方案来避免我在hackerearth中出现“超出内存”错误

问题描述

int **list, **short_list;
//num defines the number of rows and 2 defines no. of column needed
list = malloc(num * 2 * sizeof(int *));
short_list = malloc(num * 2 * sizeof(int *));

for(i = 0; i < num; i++){
    list[i] = malloc(num * 2 * sizeof(int));
    short_list[i] = malloc(num * 2 * sizeof(int));
}

虽然我已经使用指向数组的指针创建了动态内存分配,但我在hackerearth 中的一些输出出现了“超出内存限制”错误。难道这种内存分配方式是错误的。

标签: cmultidimensional-arraydynamic-memory-allocation

解决方案


你的分配有问题。在第一个malloc你得到num * 2指针,但在循环中你只初始化num这些指针。这肯定是一个错误。

num * 2此外,您在循环中再次使用似乎很奇怪。这意味着您最终会分配num * num * 2整数。这很可能不是你想要的。

如果您真的希望矩阵num * 2简单地执行:

int **list, **short_list;
//num defines the number of rows and 2 defines no. of column needed

list = malloc(num * sizeof(int *));            // Only use num here
short_list = malloc(num * sizeof(int *));

for(i = 0; i < num; i++){               
    list[i] = malloc(2 * sizeof(int));         // Only use 2 here
    short_list[i] = malloc(2 * sizeof(int));
}

num * 2分配矩阵的另一种更简单的方法是:

int (*list)[2];
list = malloc(num * sizeof *list);

推荐阅读