zoukankan      html  css  js  c++  java
  • C堆上申请二维数组

    C堆上申请二维数组

    之前写了一篇《C++堆上申请二维数组》,应该说C++的方式相对于C还是更简单容易理解一些,那么C如何写呢?

    • 方法一:通过数组指针申请连续的空间
     1 #include <stdio.h>
     2 #include <stdlib.h>
     3 int main()
     4 {
     5     // 申请a[3][2]三行两列二维数组
     6     int (*a)[2] = (int(*)[2])malloc(sizeof(int)*3*2);
     7     a[0][0] =1;
     8     a[0][1] =2;
     9     a[1][0] =3;
    10     a[1][1] = 4;
    11     a[2][0] =5;
    12     a[2][1] = 6;
    13     printf("%d\t%d\t%d\t%d\t%d\t%d\n",a[0][0],a[0][1],a[1][0],a[1][1],a[2][0],a[2][1]);
    14     printf("%x\n%x\n%x\n%x\n%x\n%x\n",(int)a,(int)&a[0][1],(int)&a[1][0],(int)&a[1][1],(int)&a[2][0],(int)&a[2][1]);
    15     free(a);
    16     return 0;
    17 }

    注意,理解指针a的类型为int(*)[2]是理解算法的关键。

    • 方法二:同C++,容易理解的,多个一维指针申请多次,但空间不连续。
    1     int **a;
    2     int i;
    3     a = (int **)malloc(sizeof(int *)*3);
    4     for (i=0; i<3; i++)
    5         a[i] = (int *)malloc(sizeof(int)*2);

    两种方法各有优劣。

    iCC Develop Center
  • 相关阅读:
    JSChart_页面图形报表
    hdu 2602(dp)
    hdu 1518(dfs)
    hdu 1716(dfs)
    hdu 1002大数(Java)
    SPOJ 375. Query on a tree (树链剖分)
    poj 1091 跳蚤
    HDU 4048 Zhuge Liang's Stone Sentinel Maze
    HDU Coprime
    HDU Machine scheduling
  • 原文地址:https://www.cnblogs.com/ccdev/p/2674789.html
Copyright © 2011-2022 走看看