I am trying to do an exercise in Stroustrup's book. The task is to create two arrays (with different values) and pointers to each array, and copy the first array to the second using the pointer and reference operators. My code is below.
#include "../../std_lib_facilities.h"
int main ()
{
int p0[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
int* p1 = &p0[0];
int q0[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
int* q1 = &q0[0];
for (int i = 0; i < 10; ++i) {
p0[i] = 2 * (i + 1);
}
for (int i = 0; i < 10; ++i) {
cout <<"Array place " << i << " has value " << p0[i] << ".\n";
}
cout << " \n";
for (int i = 0; i < 10; ++i) {
cout <<"Array place " << i << " has value " << q0[i] << ".\n";
}
cout << " \n";
cout << " \n";
q1 = p1;
q0[0] = *q1;
for (int i = 0; i < 10; ++i) {
cout <<"Array place " << i << " has value " << q0[i] << ".\n";
}
keep_window_open();
return 0;
}
The program compiles and runs. BUT the output is correct only for q[0], the first element of the second array. The values of the other array elements remain unchanged. I don't know if I think I am supposed to do is even possible. I thought the rest of the array would copy automatically after pointing to the first element (line 27). Thanks in advance for your help.