c - 有没有更好的解决方案来避免我在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 中的一些输出出现了“超出内存限制”错误。难道这种内存分配方式是错误的。
解决方案
你的分配有问题。在第一个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);
推荐阅读
- jquery - Jquery如何只找到第一次出现
- c# - 在正则表达式替换中投射 1 美元
- ios - 性能方面,这是对类、结构、枚举等进行分组的更好方法
- apache - 与 Atlas HiveMetastoreBridge 代码相关的几个问题
- python - 获取一个基类的所有子类作为基类的类属性
- github - Travis CI 修改同一分支
- scala - 比较两个数据框中列的值
- c# - 如何将数据从 List 导出到具有不同 CSV 格式的 CSV 文件
- java - Java - 如果条件检查整数数组列表是否包含大于特定值的元素
- excel - (1004) 应用程序定义或对象定义错误