I'm trying to write a method that generates 2 arrays, one of int type that has 10 random numbers and an array of int pointers that point to the elements in the regular array, then return these arrays.
Problem is that making the regular int array works just fine, but the array of pointers stops pointing to the elements as soon as the method returns back to the method that called it.
I have tried to use different copying methods such as memcpy but the same results happen.
This is the method that is supposed to build the arrays and set up the pointers.
void array_builder(int ray[], int * pointer[]){
int A[10];
int* B[10];
for (int i = 0; i < 10; i++) {
A[i] = int(rand()) % 101;
B[i] = &A[i];
//cout << B[i] << " " << *B[i] << endl;
}
array_copy(ray,A);
array_copy(pointer,A);
for (int i = 0;i<10;i++){
cout << *pointer[i] << " " << pointer[i] << endl;
}
}
This is the method that makes the pointer array point to all the elements in the normal array.
void array_copy(int* rayA[], int rayB []){
for (int i = 0;i<10;i++){
rayA[i] = &rayB[i];
}
}
When ran this is the output from the array_builder()
method:
41 0x6dfe40
85 0x6dfe44
72 0x6dfe48
38 0x6dfe4c
80 0x6dfe50
69 0x6dfe54
65 0x6dfe58
68 0x6dfe5c
96 0x6dfe60
22 0x6dfe64
Printing the same way back at the method that calls array_builder
:
41 0x6dfe40
7208416 0x6dfe44
72 0x6dfe48
7208520 0x6dfe4c
4199040 0x6dfe50
4199040 0x6dfe54
7208696 0x6dfe58
4712842 0x6dfe5c
5019744 0x6dfe60
4964389 0x6dfe64
Can someone tell me why this is happening and how to go about fixing it?