码迷,mamicode.com
首页 > 编程语言 > 详细

c语言,动态数组

时间:2015-07-24 20:10:11      阅读:120      评论:0      收藏:0      [点我收藏+]

标签:

 

试着直接malloc一个2*3*4的空间来模拟数组:

#include <stdio.h>
#include <malloc.h>

int main(void)
{

    int*** pArr = NULL;

    pArr = (int ***)malloc(2*3*4*sizeof(int));
    if(pArr == 0)
    {
        return -1;
    }
    
    memset(pArr, 0, 2*3*4*sizeof(int));

    pArr[0][0][1] = 11;
    printf("pArr[0][0][1] = %d\n" , pArr[0][0][1]);
    
    free(pArr);
    pArr = NULL;

    return 0;
}
/*
root@oucaijun:/work/dcc# gcc 1.c ;./a.out 
1.c: In function ‘main’:
1.c:17: warning: incompatible implicit declaration of built-in function ‘memset’
Segmentation fault

*/

  

创建与释放一个三维数组:

#include <stdio.h>
#include <malloc.h>

int*** Malloc3DActiveArray(int*** pArr, int x, int y, int z);
void Free3DActiveArray(int*** pArr, int x, int y);
//void Display3DArray(int*** pArr, int x, int y, int z);


int main(void)
{
    int x, y, z;
    int*** array = NULL;

    printf("输入一维长度: ");
    scanf("%d",&x);
    printf("输入二维长度: ");
    scanf("%d",&y);
    printf("输入三维长度: ");
    scanf("%d",&z);

    array = Malloc3DActiveArray(array, x, y, z);
    printf("1\n");
    printf("array[0][0][1] = %d\n", array[0][0][1]);
    Free3DActiveArray(array, x, y);
    array = NULL;

    return 0;
}

int*** Malloc3DActiveArray(int *** pArr, int x, int y, int z)
{
    int i, j, k;
    pArr = (int ***)malloc(x * sizeof(int **)); //第一维

    for (i = 0; i < x; i++)
    {
        pArr[i] = (int **)malloc(y * sizeof(int *));//第二维
        for (j = 0; j < y; j++)
        {
            pArr[i][j] = (int *)malloc(z * sizeof(int));//第三维
            for (k = 0; k < z; k++)
            {
                pArr[i][j][k] = i + j + k + 1;
                printf("%d ", pArr[i][j][k]);
            }
            printf("\n");
        }
        printf("\n");
    }
    
    return pArr;
}

void Free3DActiveArray(int*** pArr, int x, int y)
{
    int i, j;
    for (i = 0; i < x; i++)
    {
        for (j = 0; j < y; j++)
        {
            free(pArr[i][j]);//第三维
            pArr[i][j] = 0;
        }

        free(pArr[i]);//第二维
        pArr[i] = 0;
    }
    free(pArr);//第一维
}
/*
root@oucaijun:/work/dcc# gcc 1.c ;./a.out 
输入一维长度: 1
输入二维长度: 2
输入三维长度: 3
1 2 3 
2 3 4 

1
array[0][0][1] = 2

*/

  

 c语言中内存的动态分配与释放(多维动态数组构建) 

 

c语言,动态数组

标签:

原文地址:http://www.cnblogs.com/mylinux/p/4674079.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!