首页 > 解决方案 > 通过分配单个缓冲区并通过指向该缓冲区来设置 list1 和 list2 来替换两个 malloc 调用

问题描述

我正在使用合并排序函数,它包含两个使用 malloc 函数的列表。为了提高性能,我需要malloc通过分配一个缓冲区并设置list1list2指向该缓冲区来替换这两个调用。这将调用 malloc/free 的次数减少到一半。

intType* list1 = (intType*)malloc(n1*sizeof(intType));
intType* list2 = (intType*)malloc(n2*sizeof(intType));

在哪里n1 = N /2;n2 = N -2;

N是要排序的元素个数。

我尝试了不同的方法,但实施起来没有运气。有人可以帮忙吗?

标签: cperformanceoptimizationbuffer

解决方案


你可以这样做:

/* 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()家庭的铸造结果被认为是一种不好的做法


推荐阅读