Multiplying the values in an array

Hello, I need to access the elements of the array and double the value of it. For some reason, values 3 and 4 are not double correctly when compiled.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
/*
Create a function to double the value of each
element of an array by using pass-by-pointer
and the pointer notation.
*/
#include <iostream>
using namespace std;

void doubleVal(int *, int);

int main()
{
    const int SIZE = 3;
    int arr[SIZE] = {2,3,4};
    int * ptr;
    ptr = arr;

    cout << "The elements in the array are: ";
    for(int i = 0; i < SIZE; i++)
    {
        cout << *(arr+i) << " ";
    }

    cout << endl;
    doubleVal(ptr, SIZE);

    return 0;
}

void doubleVal(int * ptr1, int S)
{
    for(int i = 0; i < S; i++)
    {
        *ptr1 *= 2;
        cout << *ptr1 << endl;
    }
}
/* Output
The elements in the array are: 2 3 4
4
8
16
*/
1
2
    int * ptr;
    ptr = arr;

You're using unnecessary pointer syntax here. arr is already (effectively) a pointer (it's an array, but decays into a pointer when passed to a function).

In doubleVal, just do:
1
2
3
4
5
    for(int i = 0; i < S; i++)
    {
        ptr1[i] *= 2;
        cout << *ptr1 << endl;
    }


*ptr1 will only ever give you the first element of the array. It's the same as doing *(ptr1+0)
Last edited on
Hello Slee p,

In your function "doubleVal" "ptr1" is the address of the beginning of the array or element zero.

Your code doubles the value of "*ptr1" and stores the result in "*ptr1". Since "*ptr1" never changes it doubles the last value and stores it in "*prt1".

I believe what you want is:
1
2
ptr1[i] *= 2;
cout << ptr1[i] << endl;

I have not tested this yet, but I believe it should work.

Hope that helps,

Andy
Thank you for both of your help. My code is working correctly now!
Topic archived. No new replies allowed.