您的位置:首页 > 其它

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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: