2D array and dynamic array and dynamic 2D array
2016-05-04 08:53
381 查看
#include <stdio.h> #include <stdlib.h> #include <malloc.h> //malloc() #include <string.h> // memset() /* run this program using the console pauser or add your own getch, system("pause") or input loop */ //--------------------------------------------------------------- //以一维数组的方式遍历二维数组 void printData_1(int* a,int len) { int i = 0; for(i=0;i<len;i++) { printf("%d\n",a[i]); } } //以指针的方式遍历二维数组 void printData_2(int (*a)[3],int row) // int (*a)[3] <=> int a[][3] { int col = sizeof(*a)/sizeof(int); int i = 0; int j = 0; printf("%d\n",sizeof(a)); for(i=0;i<row;i++) { for(j=0;j<col;j++) { printf("%d\n",*(*(a+i)+j));// a[i][j] <=> *(a[i]+j) <=> *(*(a+i)+j) } } } //--------------------------------------------------------------- //------------------重置一维动态空间的大小----------------------- int reset(int** p,int size,int new_size) { int ret = 1; int len = 0; int i = 0; int* pt = NULL; int* tmp = NULL; int* pp = *p; if((p!=NULL)&&(new_size>0)) { pt = (int*)malloc(sizeof(int) * new_size); memset(pt,0,sizeof(int) * new_size); tmp = pt; //做了一个替身tmp len = (size<new_size)?size:new_size; for(i=0;i<len;i++) { *tmp++ = *pp++; } free(p); *p = pt; // 很重要 } else { ret = 0; } return ret; } void test_1() { int* p = (int*)malloc(sizeof(int)*4); int i = 0; int length = 0; p[0] = 1; p[1] = 2; p[2] = 3; p[3] = 4; printf("%x\n",p); length = 8; if( reset(&p,4,length) ) { printf("%x\n",p); } for(i=0;i<length;i++) { printf("%d\n",p[i]); } free(p); } //--------------------------------------------------------------- //--------------------动态申请二维数组--------------------------- int** malloc2d(int row,int col) { int** ret = NULL; int* p = NULL; int i = 0; ret = (int**)malloc(sizeof(int*)*row); p = (int*)malloc(sizeof(int)*row*col); if((ret!=NULL)&&(p!=NULL)) { for(i=0;i<row;i++) { ret[i] = p + i * col; } } else { free(p); free(ret); ret = NULL; } return ret; } void free2d(int** a) { free(&a[0][0]); //这里的free顺序很重要 free(a); } void test_2() { int row = 2; int col = 3; int** a = malloc2d(row,col); int i = 0; int j = 0; for(i=0;i<row;i++) { for(j=0;j<col;j++) { *(*(a+i)+j) = j ; } } printData_1(&a[0][0],row*col); // &a[0][0] <=> a free2d(a); } //---------------------------------------------------------------- int main(int argc, char *argv[]) { int a[3][3] = {{0,1,2},{3,4,5},{6,7,8}}; //printData_1(&a[0][0],9); printData_2(a,3); //test_1(); return 0; }
相关文章推荐
- 《Effective java》-----读书笔记
- 数学分支之一
- eciplise android 出现导入不了layout文件的解决方法
- 112. Path Sum
- 233. Number of Digit One
- 第一课程序框架的构建——C#计算器编程教学
- 关于oracle 实例名大小写的问题
- php 函 数
- 为什么UDP有时比TCP更有优势?
- WebMvcConfigurationSupport
- 汉诺塔
- 《java入门第一季》之面向对象(匿名对象)
- Retrofit2.0+网络框架HTTP实战
- 《java入门第一季》之面向对象(匿名对象)
- 虚拟机已死,容器才是未来?
- array used and char`s array and string`s array
- am335x开发板的疑问以及解答
- 浅谈盒模型
- Android 模拟器的创建
- ajax