两种创建二维动态数组效率对比
  MJlmRDrYd0Ow 2023年11月02日 60 0


#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// fun1使用方式1创建n行m列动态二维整数数组
void fun1(int n, int m) {
int **array1 = (int **)malloc(n * sizeof(int *));
int i = 0;
int j = 0;
for (;i < n;i++) {
array1[i] = (int *)malloc(m * sizeof(int));
}
for (;i < n;i++) {
for (;j < m;j++) {
array1[i][j] = i * j;
}
}
for (i = 0;i < n;i++) {
free(array1[i]);
}
free(array1);
}
// fun2使用方式2创建n行m列动态二维整数数组
void fun2(int n, int m) {
int **array2 = (int **)malloc(n * sizeof(int *));
array2[0] = (int *)malloc(m * n * sizeof(int));
int i = 0;
for (i = 1;i < n;i++) {
array2[i] = array[0] + i * m;
}
free(array2[0]);
free(array2);
}
int main() {
fun1(10, 100); // fun2性能优于fun1
fun2(10, 100);

return 0;
}

方式和方式2的内存分配如下:

两种创建二维动态数组效率对比_c语言

方式2内存分配是连续的,而且malloc和free次数更少,因此性能更高。

#编译
gcc -g -o Test test.c
#使用valgrind查内存泄漏
valgrind --tool=memcheck --leak-check=full --show-leak-kinds=all ./Test

 

【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年11月08日 0

暂无评论

推荐阅读
  4WdcduV19eWs   2023年11月02日   64   0   0 ios#includeios#include
  4WdcduV19eWs   2023年11月02日   62   0   0 ios#includeios#include
  4WdcduV19eWs   2023年11月02日   66   0   0 ios#includeios#include
  4WdcduV19eWs   2023年11月02日   53   0   0 ios#includeios#include
  4WdcduV19eWs   2023年11月02日   42   0   0 ios#includeios#include
  4WdcduV19eWs   2023年11月02日   65   0   0 ios#includeios#include
  4WdcduV19eWs   2023年11月02日   87   0   0 ios#includeios#include
  4WdcduV19eWs   2023年11月02日   51   0   0 ios#includeios#include
  4WdcduV19eWs   2023年11月02日   78   0   0 #includelinuxlinux#include
MJlmRDrYd0Ow