Pointers

Hello Everyone!

I am having a problem copying a dynamically allocated array from one pointer to another. The error in my program comes after I enter the values of the dynamically allocated array and attempt to print them out. Any help would be greatly appreciated! Here is what I have so far:

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
#include <iostream>
using namespace std;

void getVals(double *&dPtr);
void printVals(double *dPtr);
double size;

int main() 
{
	double *dPtr;
	getVals(dPtr);
	printVals(dPtr);

}

void getVals(double *&dPtr)
{
	double *d2Ptr;
	cout << "Please enter the number of values you would like to be in your array!";
	cin >> size;
	d2Ptr = new double[size];
	for(int i=0; i<size; i++) {
		cout << "Please enter the value of array item #" << i+1 << ": ";
		cin >> d2Ptr[i];
	}
	d2Ptr = dPtr;
}

void printVals(double *dPtr)
{
	for(int i=0; i<size; i++) {
		cout << "The value of array item #" << i+1 << " is: " << dPtr[i] << endl;
	}
}
Last edited on
Your have a problem with this function:
1
2
3
4
5
6
7
8
9
10
11
12
void getVals(double *&dPtr)
{
	double *d2Ptr;
	cout << "Please enter the number of values you would like to be in your array!";
	cin >> size;
	d2Ptr = new double[size];
	for(int i=0; i<size; i++) {
		cout << "Please enter the value of array item #" << i+1 << ": ";
		cin >> d2Ptr[i];
	}
	d2Ptr = dPtr; //<<==Problem with this statement
}



PS. If you are going to pass a reference to a pointer as a function parameter, then there is no need to create a separate pointer to hold the array and then assign this pointer to the reference pointer..
Which is a complicated way of saying that d2Ptr is not needed - just use dPtr
Last edited on
Okay, that is where I thought I was having the problem. However, I am unsure on how to fix it. Would I just need to copy the d2Ptr into dPtr using a for loop? If so, would it just be something like this?

1
2
3
for(int k=0; k<size; k++) {
    d2Ptr[i] = dPtr[i];
}
In the original code - dPtr = d2Ptr NOT d2Ptr = dPtr;
Oh ok so I was just assigning it backwards...thanks.
Topic archived. No new replies allowed.