欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

循环读取数组元素的3种写法

程序员文章站 2022-07-11 09:32:39
``` // main.cpp // array // Created by mac on 2019/4/4. // Copyright © 2019年 mac. All rights reserved. // 循环读取数组元素的3种写法 include using namespace std; i ......
//  main.cpp
//  array
//  created by mac on 2019/4/4.
//  copyright © 2019年 mac. all rights reserved.
// 循环读取数组元素的3种写法
#include <iostream>
using namespace std;
int main(int argc, const char * argv[]) {
    int a[10]={1,2,3,4},*p;
    int sum,i;
    //常规写法不用指针
    for (sum=a[0],i=1;i<10;i++) {
        sum+=a[i];
    }
    //把数组名a当作指针,但是a是个常量的指针
    for (sum= *a,i=1; i<10; i++) {
        sum+=*(a+i);
    }
    //定义指针变量指向数组名
    //比较有意思的是 这个p可以知道字节数 知道可以跳到下一个字节
    // p+1相当于p+sizeof(int)*1
    for (sum=*a,p=a+1; p<a+10; p++) {
        sum+=*p;
    }
    cout<<sum<<endl;
    return 0;
}