有什么更好的解决方案来避免我在hackerearth中的“内存超出”错误

时间:2019-01-10 03:37:02

标签: c multidimensional-array dynamic-memory-allocation

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中我的一些输出却遇到了“超出内存限制”错误。这种内存分配方式是错误的吗?

1 个答案:

答案 0 :(得分:3)

您的分配有问题。在第一个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);