Pointer help

thanks
Last edited on
I would have it just return the sum instead of messing around with new and pointers.

So something like
1
2
3
4
5
6
7
8
9
10
11
12
13
14
int calcSum(int arr[], int n)
{
    int sum = 0;
    for (int i = 0; i < n; ++i)
        sum += arr[i];
    return sum;
}

int main()
{
    int nums[4] = {9, 63, 1, 3};
    int sum = calcSum(nums, 4);
    cout << "The sum is " << sum << endl;
}

If you really insist on using a pointer, do this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
void calcSum(int arr[], int n, int* pToSum)
{
    *pToSum = 0;
    for (int i = 0; i < n; ++i)
        *pToSum += arr[i];
}

int main()
{
    int nums[4] = {9, 63, 1, 3};
    int sum;
    calcSum(nums, 4, &sum);
    cout << "The sum is " << sum << endl;
}

If you really, really don't want to change main at all, you'll have to resort to something like
1
2
3
4
5
6
void calcSum(int arr[], int n, int** pToSum)
{
    *pToSum = new int(0);
    for (int i = 0; i < n; ++i)
        **pToSum += arr[i];
}
but note that there's a memory leak here since you didn't delete ptr; in main.
Topic archived. No new replies allowed.