-7
int main()
{

    int x=5,y=5;
    int sum = add(&x,&y);

    cout<<"Address of x is"<<&x<<endl;
    cout<<"Address of y is"<<&y<<endl;
    cout<<"The addition of a and b is"<<sum<<endl;

    int a[5]={1,2,3,4,5};
    int *p1;
    p1=a;

    for(int i=0;i<5;i++)
    {
        cout<<"The Address of the Array elements is"<<p1+i<<endl;
        cout<<"The value of the array element is"<<*(p1+i)<<endl;
    }
    cout<<endl;
    cout<<endl;
    for(int i=0;i<5;i++)
        {
            cout<<"The Address of the Array elements is"<<&p1[i]<<endl;
            cout<<"The value of the array element is"<<p1[i]<<endl;
        }

    cout<<"address of a is "<<p1<<endl;
    int arrayTotal= SumofArray(a,5);
    cout<<"The sum of array is"<<arrayTotal <<endl;
}

I started to learn to code and I believe, I have to be strong with pointers to code in c++ and make efficient programs.

when we assign p1=a;

Literally i can use a[i] or p[i]? I am confused between this difference. The above snippet works tho I am curious if some one can explain in detail.

Thanks

user0042
  • 7,691
  • 3
  • 20
  • 37
AmithRc
  • 59
  • 6
  • 1
    Please before posting a question check whether it already exists or not otherwise by time you'll get blocked from posting. – Raindrop7 Aug 23 '17 at 20:59
  • 1
    _"... and I believe, I have to be strong with pointers to code in c++ and make efficient programs."_ No that's the completely wrong attitude to approach c++. You shouldn't deal with raw pointers or raw arrays in 1st place. There's c++ standard library support with `std::array` and `std::vector`. – user0042 Aug 23 '17 at 21:00
  • 2
    Being "strong with pointers" is **a lot** less important than beginners seem to think, at least in this millennium. – Baum mit Augen Aug 23 '17 at 21:00
  • 1
    @Baum It's what their stupid teachers/professors want to see. I'm really pissed off to finance these people with my taxes paid. – user0042 Aug 23 '17 at 21:02
  • Went with Unclear already, but [this](https://stackoverflow.com/q/4810664/3002139) may be a good dupe target. – Baum mit Augen Aug 23 '17 at 21:05
  • *I have to be strong with pointers to code in c++ and make efficient programs.* -- In a lot of situations, using pointers too much causes the compiler's optimizer to skip your code. Thus the result is slower programs by overusing pointers, not more efficient ones. – PaulMcKenzie Aug 23 '17 at 21:43

1 Answers1

1

Literally i can use a[i] or p1[i]?

Yes, dereferencing works the same way for a raw array symbol or a pointer.

The a symbol in your example will decay to a int* pointer whenever used as such (p1=a;).

Using code like p1[i] is just syntactic sugar for *(p1 +i).

user0042
  • 7,691
  • 3
  • 20
  • 37