C语言--二维数组的使用

    今天使用二维数组,纠结使用固定大小还是动态分配内存。动态分配内存不熟练,总倾向于分配固定大小的内存,这样不好。所以把两种都实现一下。

1、固定大小的数组

#include <stdio.h>

#define ROW 5
#define COLUMN 6

void main(void)
{
    int i = 0;
    int j = 0;
    int int_array[ROW][COLUMN];
    
    for(i = 0;i < ROW;i++)
    {
        for(j = 0;j < COLUMN;j++)
        {
            int_array[i][j] = (i * COLUMN) + j + 1;
        }
    }
    
    for(i = 0;i < ROW;i++)
    {
        for(j = 0;j < COLUMN;j++)
        {
            printf("%2d ",int_array[i][j]);
        }
        printf("\n");
    }
}
输出结果:

[root@localhost test]# ./a.out 
 1  2  3  4  5  6 
 7  8  9 10 11 12 
13 14 15 16 17 18 
19 20 21 22 23 24 
25 26 27 28 29 30 


2、动态分配内存

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

void main(void)
{
    int row = 0;
    int column = 0;
    int i = 0;
    int j = 0;
    int **p_int_array;
    
    do
    {
        printf("attention:the num you input can not be 0!\n");
        printf("please input the row of int_array:");
        scanf("%d",&row);
        printf("please input the column of int_array:");
        scanf("%d",&column);
    }while(0 == row * column);
    
//malloc memory    
    p_int_array = (int **)malloc(row * sizeof(int *));
    if(NULL == p_int_array)
    {
        printf("malloc memory fail\n");
        return;
    }
    for(i = 0;i < row;i++)
    {
        p_int_array[i] = (int *)malloc(column * sizeof(int));
        if(NULL == p_int_array[i])
        {
            printf("malloc memory fail\n");
            return;
        }
    }

//save int num
    for(i = 0;i < row;i++)
    {
        for(j = 0;j < column;j++)
        {
            p_int_array[i][j] = (i * column) + j + 1;
        }
    }
//print
    for(i = 0;i < row;i++)
    {
        for(j = 0;j < column;j++)
        {
            printf("%2d ",p_int_array[i][j]);
        }
        printf("\n");
    }
    
//free memory
    for(i = 0;i < row;i++)
    {
        free(p_int_array[i]);
        p_int_array[i] = NULL;
    }
    free(p_int_array);
    p_int_array = NULL;
    
}
输出结果:

root@localhost test]# ./a.out 
attention:the num you input can not be 0!
please input the row of int_array:9
please input the column of int_array:10
 1  2  3  4  5  6  7  8  9 10 
11 12 13 14 15 16 17 18 19 20 
21 22 23 24 25 26 27 28 29 30 
31 32 33 34 35 36 37 38 39 40 
41 42 43 44 45 46 47 48 49 50 
51 52 53 54 55 56 57 58 59 60 
61 62 63 64 65 66 67 68 69 70 
71 72 73 74 75 76 77 78 79 80 
81 82 83 84 85 86 87 88 89 90 

3、对比分析

    固定大小的数组比较简单,代码比较少,但缺点比较明显,大小固定,不修改代码就不能改变大小,实际应用的时候可能内存大但不使用造成内存的浪费,也可能内存小,存不下需要的数据。

    动态分配内存大小比较灵活,可以根据需要分配,既不浪费内存,也不会出现越界。但是涉及到动态分配内存,如果不注意释放,有可能造成内存泄漏。而且相对来说,代码比固定大小的代码多。

    综合对比,对于无法预知数据量有多少时,使用动态分配内存。如果很确定实际应用时存储数据的大小,那可以使用固定大小的数组。

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值