13.10 Write a function in C called my2DAlloc which allocates a two-dimensional array. Minimize the number of calls to malloc and make sure that the memory is accessible by the notation arr[i][j].

这道题让我们写个C语言函数my2DAlloc用来给一个二维数组分配内存,并且让我们尽可能的少调用malloc函数。一个二维数组实际是数组的数组,我们用指针来表示数组,用双指针来表示二维数组。我们首先建立一个一维数组,对于每个位置,再建立一个一维数组,这样我们就得到了一个二维数组,参见如下代码:

int** my2DAlloc(int rows, int cols) {
int **rowptr = (int**)malloc(rows * sizeof(int*));
for (int i = ; i < rows; ++i) {
rowptr[i] = (int*)malloc(cols * sizeof(int));
}
return rowptr;
}

关于释放内存,我们不能仅仅释放rowptr,我们要确保每个cell中的内存也被释放了,参见如下代码:

void my2DDealloc(int **rowptr, int rows) {
for (int i = ; i < rows; ++i) {
free(rowptr[i]);
}
free(rowptr);
}

其实我们还可以在连续的内存块上来分配内存,例如对于一个5行6列的二维数组,我们可以在开头的五个内存块里存上每一行的起始地址,后面的五行数据是连续排列的,一行接着一行,参见代码如下:

class Solution {
public:
int** my2DAlloc(int rows, int cols) {
int header = rows * sizeof(int*);
int data = rows * cols * sizeof(int*);
int **rowptr = (int**)malloc(header + data);
if (rowptr == NULL) return NULL;
int *buf = (int*)(rowptr + rows);
for (int i = ; i < rows; ++i) {
rowptr[i] = buf + i * cols;
}
return rowptr;
}
};

这样申请连续的一段内存空间的好处是只需要调用一次malloc就行,而且在释放的时候也不需要特别的写函数来free,好处还是蛮多的。

[CareerCup] 13.10 Allocate a 2D Array 分配一个二维数组的更多相关文章

  1. [CareerCup] 11.6 Search a 2D Matrix 搜索一个二维矩阵

    11.6 Given an M x N matrix in which each row and each column is sorted in ascending order, write a m ...

  2. [LeetCode] Search a 2D Matrix 搜索一个二维矩阵

    Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the follo ...

  3. [LeetCode] 74. Search a 2D Matrix 搜索一个二维矩阵

    Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the follo ...

  4. 数组(Array),二维数组,三维数组

    数组(Array):相同类型数据的集合就叫做数组. (一)定义数组的方法: A) type[] 变量名 = new type[数组中元素的个数] 例如: int[] a = new int[10] ; ...

  5. [leetcode]304Range Sum Query 2D - Immutable动态规划计算二维数组中子数组的sum

    303一维数组的升级版,方法就是用二维数组res存下从(0,0)到当前位置的sum,存的方法是动态规划,看着二维数组画圈比较好搞清楚其中的加减法 算子数组的sum的时候也是和存差不多的逻辑,就是某一部 ...

  6. [LeetCode] Search a 2D Matrix II 搜索一个二维矩阵之二

    Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the follo ...

  7. [LeetCode] 240. Search a 2D Matrix II 搜索一个二维矩阵 II

    Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the follo ...

  8. Java使用Array类创建多维数组

    1.创建一维数组 import java.lang.reflect.Array; public class ArrayTest { public static void main(String[] a ...

  9. c指针与数组,传参问题,指针数组与数组指针的区别,二维数组动态内存分配

    一 数组的结构:顺序存储,看谭浩强中的图,牢记 1.数组名指代一种数据结构:数组 现在可以解释为什么第1个程序第6行的输出为10的问题,根据结论1,数组名str的内涵为一种数据结构,即一个长度为10的 ...

随机推荐

  1. javascript 的字符串原生方法

    join([分隔符])数组元素组合为字符串 toString()以字符串表示数组 reverse()数组反转--改变原数组本身 valueOf()返回数组值 <html> <head ...

  2. [QualityCenter]设置工作流脚本-设置不同字段值关联不同列表

    需求:当选择A字段某个值时,设置B字段的列表值根据A字段的值来判断读取不同的列表值,如当运行省份的值已更改, 运行地区的选择列表将更改. 在脚本编辑器新建一个函数UserFuntion_Bug_Pro ...

  3. 转 HighCharts笔记之: Bar Chart

    最近需要做一些Web图标,研究了几个开源的第三方工具后,最后决定使用HighCharts开发: Highcharts 是一个用纯JavaScript编写的一个图表库, 能够很简单便捷的在web网站或是 ...

  4. java工程中的相关路径

    一.路径 绝对路径: 指的是文件在系统中的真实路径(物理路径). 相对路径: 指的是文件相对某个目录的相对路径. 对于java application 工程来说,当编写完一个类之后,class文件会编 ...

  5. HTTP Session原理

    深入理解HTTP Session   session在web开发中是一个非常重要的概念,这个概念很抽象,很难定义,也是最让人迷惑的一个名词,也是最多被滥用的名字之一,在不同的场合,session一次的 ...

  6. c#的序列化与反序列化

    这是反序列化的代码 using System.Runtime.Serialization.Json; public static T deserialize<T>(String s) { ...

  7. 计算几何--求凸包模板--Graham算法--poj 1113

    Wall Time Limit: 1000MS   Memory Limit: 10000K Total Submissions: 28157   Accepted: 9401 Description ...

  8. Linux shell basic3 dd wc comm chmod ls

    Generating files of any size /dev/zerois a character special device, which infinitely returns the ze ...

  9. Load xlsx in a folder to RDBMS table with Talend

    Step 1 . Use tFileList component to get the file list. And set proper property. Step 2. Use tFileInp ...

  10. MSBI--enlarge the DW database table volume

    我们在学习MSBI的时候,经常会使用官方提供的Adventureworks和AdventureworksDW示例数据库,但是官方提供的数据量有点小, 以DW为例,Factinternetsales只有 ...