-1

So, I was told to... "Write a function Adder() that receives a pointer to an integer array as input, and uses this pointer to return the sum of elements of the array." And I was pretty successful. My code is

#include <bits/stdc++.h>
using namespace std;

int Adder (int *ptr)
{
    int sum=0;
    for (int i=0; i<5; i++)
    {
        sum=*(ptr+i)+sum;
    }
    return sum;
}

int main(){
    int array[5]={1,1,1,1,1};
    int sum;
    int *ptr=array;
    Adder(ptr);
    sum=Adder(ptr);
    cout<<sum;
}

The thing I can't understand is where I

Adder(ptr)

and then

int Adder (int *ptr)

"ptr" holds the address, right? While, " *ptr " holds the actual value. I can't understand how this worked. Can someone please explain?

WhozCraig
  • 65,258
  • 11
  • 75
  • 141
  • `ptr` hols the address while `*ptr` is the value the pointer pointing to. `*` is called dereferencing operator. It dereference the pointer to get the value it points to – asmmo Jan 01 '20 at 21:53
  • Your question is not clear. what's the thing you are asking about – asmmo Jan 01 '20 at 21:54
  • also [stop including ``](https://stackoverflow.com/q/31816095/995714) – phuclv Jan 02 '20 at 12:39

2 Answers2

0

The line

int Adder (int *ptr)

defines a function that takes a pointer to an int as its argument. In this context, *ptr does not refer to the value ptr is pointing to.

The line

Adder(ptr);

invokes that function, passing the local pointer named ptr.

jkb
  • 2,376
  • 1
  • 9
  • 12
0

The reason why this works is because adding 1 to an int pointer (in your case ptr) will actually add the size of an int (which can vary depending on the machine).

See the answers to this question for a more detailed explanation: Why a pointer + 1 add 4 actually