c - 通过分配单个缓冲区并通过指向该缓冲区来设置 list1 和 list2 来替换两个 malloc 调用
问题描述
我正在使用合并排序函数,它包含两个使用 malloc 函数的列表。为了提高性能,我需要malloc
通过分配一个缓冲区并设置list1
并list2
指向该缓冲区来替换这两个调用。这将调用 malloc/free 的次数减少到一半。
intType* list1 = (intType*)malloc(n1*sizeof(intType));
intType* list2 = (intType*)malloc(n2*sizeof(intType));
在哪里n1 = N /2;
和n2 = N -2;
N
是要排序的元素个数。
我尝试了不同的方法,但实施起来没有运气。有人可以帮忙吗?
解决方案
你可以这样做:
/* allocate buffer for the two arrays */
intType* list1 = malloc((n1 + n2) * sizeof(intType));
/* assign pointer with offset */
intType* list2 = list1 + n1;
/* some works */
free(list1);
另请注意,malloc()
家庭的铸造结果被认为是一种不好的做法。
推荐阅读
- android - 如何为任务添加片段范围的侦听器?
- excel - 我需要复制活动单元格旁边的 6 个单元格
- python - 我只想用这些方法得到更有效的答案
- openxml - 打开 Xml - 需要修复文件才能打开
- xml - XML 样式表解析字段获取第一个空格左侧的任何内容
- android - 连接并快速断开连接后,我的 BLE 模块对其他设备变得不可见,即使我停止了应用程序
- r - 在函数中设置子集时如何指定列?
- python - Why node.js prints the PythonShell variable?
- python - 使用 Python 生成词频图的方法?
- go - 我可以依赖基于发送顺序的选择唤醒顺序吗?