指针、一维数组、二维数组

// exam3.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include<iostream>
using namespace std;


/*

数组
1 2 8 9

2 4 9 12
4 7 10 13
6 8 11 15

*/

int array[4][4] = {{1,2,8,9},{2,4,9,12},{4,7,10,13},{6,8,11,15}};
//将数组作为形参,遍历数组
void print1(int arr[],int size)
{
for(int i = 0;i<size;i++)
cout<<arr[i]<<" ";
cout<<endl;
}
//将一维数组的指针作为形参,指针遍历数组

void print2(int * arr,int size)
{
for(int i = 0;i<size;i++)
cout<<*(arr+i)<<" ";
cout<<endl;
}


int _tmain(int argc, _TCHAR* argv[])
{
printf("hello world!\n");
/******************一维数组和指针**************************/
cout<<"***********一维数组和指针**************"<<endl;
int arr[] ={1,2, 3, 4 ,5 ,6 ,7, 8,9};
//1.1、一维数组:采用数组下标的方式遍历
cout<<"采用数组下标的方式遍历数组!"<<endl;
for(int i = 0;i<9;i++)
cout<<arr[i]<<" ";
cout<<endl;
//1.2、指针方式遍历
cout<<"采用指针方式遍历数组!"<<endl;
int * it =arr;//将指针的值为arr的首地址
for(int i = 0;i<9;i++)
cout<<*(it+i)<<" ";
cout<<endl;
//1.3、将数组作为形参,传递给函数
cout<<"将数组作为形参,数组下标方式遍历数组!"<<endl;
print1(arr,9);
//1.4、将数组作为形参,传递给函数
cout<<"将一维数组的指针作为形参,指针遍历数组"<<endl;
print2(it,9);

/******************二维数组和指针**************************/
cout<<endl<<endl;
cout<<"***********二维数组和指针**************"<<endl;

//二维数组:采用数组下标的方式遍历
cout<<"采用数组下标的方式遍历数组!"<<endl;
for(int i=0;i<4;i++)
{
for(int j=0;j<4;j++)
cout<<array[i][j]<<" ";
cout <<endl;
}

//二维数组:采用指针的方式遍历
cout<<"采用指针的方式1遍历数组!"<<endl;
int* iter1 =(int*)(array);
for(int i=0;i<4;i++)
{
for(int j=0;j<4;j++)
cout<<*(iter1+4*i+j)<<" ";
cout <<endl;
}
//二维数组:采用指针的方式遍历
cout<<"采用指针的方式2遍历数组!"<<endl;
int** iter2 =(int**)(array);
for(int i=0;i<4;i++)
{
for(int j=0;j<4;j++)
cout<<int(*(iter1+4*i+j))<<" ";
cout <<endl;
}
//二维数组:采用指针的方式遍历
cout<<"采用指针数组的方式2遍历数组!"<<endl;
int(*iter3)[4] =array;
for(int i=0;i<4;i++)
{
for(int j=0;j<4;j++)
cout<<*(*(iter3+i)+j)<<" ";
cout <<endl;
}

return 0;
}

 

posted @ 2016-08-04 15:32  Axel_uestc  阅读(329)  评论(0编辑  收藏  举报