使用malloc分配二維數組的兩種方法


方法一:

#include <malloc.h>
#include <stdio.h>
int main()
{
    int **a = malloc(sizeof(int)*3);
    a[0]= malloc(sizeof(int)*2);
    a[1]= malloc(sizeof(int)*2);
    a[2]= malloc(sizeof(int)*2);
    a[0][0] =1;
    a[0][1] =2;
    a[1][0] =3;
    a[1][1] = 4;
    a[2][0] =5;
    a[2][1] = 6;
    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]);
    free(a[0]);
    free(a[1]);
    free(a[2]);
    free(a);
}

方法二:

#include <malloc.h>
#include <stdio.h>
int main()
{
    int (*a)[2] = malloc(sizeof(int)*3*2);
    a[0][0] =1;
    a[0][1] =2;
    a[1][0] =3;
    a[1][1] = 4;
    a[2][0] =5;
    a[2][1] = 6;
    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]);
    free(a);
}

 

文章轉自:http://blog.csdn.net/todd911/article/details/7915753


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM