0

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?

  • 6
    `A` does not exist after your method returns – smac89 Sep 16 '19 at 04:00
  • Wow, I've been looking this for hours now and thats all it was... – NextGenFarmer Sep 16 '19 at 04:04
  • Note, I'm not simply saying to make `A` global, but rather to realize that you have taken the address of a temporary variable. Once your function returned to it's caller, `A` does not exist in memory (stack) anymore, so the address of its content is also invalid – smac89 Sep 16 '19 at 04:07
  • I see, I swapped ```A``` with ```ray``` and everything seems to be working now – NextGenFarmer Sep 16 '19 at 04:10
  • 1
    Please find a course that doesn't use C, a lot of difficulties in C++ are C legacy. Use std:: vector or std::array instead and it will be easier to learn! – JVApen Sep 16 '19 at 05:44
  • 1
    Possible duplicate of [What is a dangling pointer?](https://stackoverflow.com/questions/17997228/what-is-a-dangling-pointer) – L. F. Sep 16 '19 at 10:26

0 Answers0