数组元素的遍历,在C++中可用两种方法简单实现,举例如下:
新建一个win32的控制台应用程序,输入如下代码:
// TEST2.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
using namespace std;
int main(int argc, char* argv[])
{
//cout<<123; //输出123
//cout<<"\n"; //换行
int ia[5]={1,2,3,4,5}; //定义数组
int i=NULL;
//通过下标来遍历
cout<<"\n"<<"通过下标来遍历数组:\n";
for (i=0;i<5;++i)
{
cout<<ia[i]<<"\n";
}
//通过指针来遍历
cout<<"\n"<<"通过指针来遍历数组:\n";
int * ip=NULL;
ip=ia;
for (ip=ia;ip<(ia+5);++ip)
{
cout<<*ip<<"\n";
}
return 0;
}
必须使用命名空间std
否则会提示cout未声明的符号
数组名即代表数组首地址,即数组第一个元素的内存地址
数组各元素的内存地址是连续的,所以可以进行加减,跨度为单个元素所占的内存大小