C实现任意行数,任意列数的二维数组

#include <stdio.h>

#include <malloc.h>

typedef int SInt32;

typedef unsigned char Data;

/*

结构:Array2D

功能:任意行数,任意列数的二维数组

注意:Array2D类型的变量在使用前一定要初始化

Array2D array2D;InitArray2D(&array2D, 8, 6);),

在使用结束后一定要销毁(DestroyArray2D(&array2D);),

销毁后可以重新初始化,重新使用。

*/

typedef struct

{

     Data ** data_;

     SInt32 rows_;

     SInt32 cols_;

}Array2D;

void InitArray2D(Array2D * pArray2D, SInt32 rows, SInt32 cols)

{

     Data ** data = (Data **)malloc(sizeof(Data *) * rows);

     SInt32 i = 0;

     while(i < rows)

         data[i++] = (Data *)malloc(sizeof(Data) * cols);

     pArray2D->data_ = data;

     pArray2D->rows_ = rows;

     pArray2D->cols_ = cols;

}

void DestroyArray2D(Array2D * pArray2D)

{

     const SInt32 rows = pArray2D->rows_;

     Data ** const data = pArray2D->data_;

     SInt32 i = 0;

     while(i < rows)

         free(data[i++]);

     free(data);

     pArray2D->data_ = 0;

     pArray2D->rows_ = 0;

     pArray2D->cols_ = 0;

}

int main(int argc, char *argv[]) /* 测试代码*/

{

     Array2D array2D;

     int i;

     int j;

     InitArray2D(&array2D, 8, 6);

     for(i = 0; i != array2D.rows_; ++i)

         for(j = 0; j != array2D.cols_; ++j)

              array2D.data_[i][j] = i + j;

     for(i = 0; i != array2D.rows_; ++i)

     {

         for(j = 0; j != array2D.cols_; ++j)

              printf("%d/t", array2D.data_[i][j]);

         printf("/n");

     }

     printf("/n");

     DestroyArray2D(&array2D);

     InitArray2D(&array2D, 7, 7);

     for(i = 0; i != array2D.rows_; ++i)

         for(j = 0; j != array2D.cols_; ++j)

              array2D.data_[i][j] = i * j;

     for(i = 0; i != array2D.rows_; ++i)

     {

         for(j = 0; j != array2D.cols_; ++j)

              printf("%d/t", array2D.data_[i][j]);

         printf("/n");

     }

     printf("/n");

     DestroyArray2D(&array2D);

     return 0;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值