指针与数组的对比

指针与数组的对比

C++/C 程序中,指针和数组在不少地方可以相互替换着用,让人产生一种错觉,以 为两者是等价的。 数组要么在静态存储区被创建(如全局数组),要么在栈上被创建。数组名对应着(而 不是指向)一块内存,其地址与容量在生命期内保持不变,只有数组的内容可以改变。 指针可以随时指向任意类型的内存块,它的特征是“可变”,所以我们常用指针来操 作动态内存。指针远比数组灵活,但也更危险。

 

 1 #include <iostream>
 2 
 3 /* run this program using the console pauser or add your own getch, system("pause") or input loop */
 4 using namespace std;
 5 int main(int argc, char** argv) {
 6         //声明数组和变量
 7     int a[5],i,sum;
 8     double avg;
 9     
10     //从键盘上循环为数组赋值
11     for (i=0;i<5;i++) {
12         cout<<"a["<<i<<"]=";
13         cin>>a[i];
14     }
15 
16     //直接显示数组元素
17     cout<<a[0]<<a[1]<<a[2]<<a[3]<<a[4]<<endl;
18     
19     //利用for循环显示数组各元素的值
20     for (i=0;i<5;i++)
21         cout<<a[i]<<"  ";
22     cout<<endl;
23 
24     //计算数组元素之和,并显示计算结果
25     sum=a[0]+a[1]+a[2]+a[3]+a[4];
26     cout<<"sum="<<sum<<endl;
27 
28     //利用循环计算数组的累加和
29     for (sum=0,i=0;i<5;i++)
30         sum+=a[i];
31 
32     //显示累加和及平均值
33     cout<<"sum="<<sum<<endl;
34     avg=sum/5.0;
35     cout<<"avg="<<avg<<endl;
36     return 0;
37 }

 

posted @ 2018-08-02 12:15  borter  阅读(155)  评论(0编辑  收藏  举报