通过分配单个缓冲区替换两个malloc调用,并通过指向该缓冲区设置list1和list2
我使用的是合并排序函数,它包含两个使用malloc函数的列表。为了提高性能,我需要分配一个缓冲区并设置通过分配单个缓冲区替换两个malloc调用,并通过指向该缓冲区设置list1和list2,c,performance,optimization,buffer,C,Performance,Optimization,Buffer,我使用的是合并排序函数,它包含两个使用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是要排序的元素数 我尝试了不同的方法,但没有成功实现
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()
系列的强制转换结果是。您可以这样做:
/* 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()
系列的强制转换结果很小。请注意,只有在两种类型相同的情况下,这才很容易实现。如果两个列表有不同的对齐要求,则可能需要添加额外的填充,以确保第二个列表正确对齐。非常感谢。它成功了:)@SalmanKhan既然答案解决了您的问题,请接受它-请注意,只有在两种类型相同的情况下,这才很容易奏效。如果两个列表有不同的对齐要求,则可能需要添加额外的填充,以确保第二个列表正确对齐。非常感谢。它起作用了:)@SalmanKhan既然答案解决了你的问题,请接受它-参见“andn2=N-2;
”:你是说“andn2=N-n1;
”?是的,我道歉。其n2=N-n1;“和n2=N-2;
”:你的意思是“和n2=N-n1;
”?是的,我道歉。其n2=N-n1;