/*
Create a function to double the value of each
element of an array by using pass-by-pointer
and the pointer notation.
*/
#include <iostream>
usingnamespace std;
void doubleVal(int *, int);
int main()
{
constint 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
*/
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)
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.