LHC2012
LHC2012

Reputation: 207

Why pointer after first iteration points to random values?

Here is my code, and I thought that each cout line will print the respective object the pointer points to. Why is there an error? This prints some random list of numbers, with first always correct.

int* f()
{
    int array[10] = {1,2,3,4,5,6,7,8,9,10};
    int *p = array;
    return p;
}

int main()
{
    int* ptr = f();
    cout << *(ptr+0) << endl;
    cout << *(ptr+1) << endl;
    cout << *(ptr+2) << endl;
    cout << endl;

}

Upvotes: 2

Views: 91

Answers (2)

Abhishek Chandel
Abhishek Chandel

Reputation: 1354

Local arrays are created on the stack, and have automatic storage duration. In your case array is created on the stack and get destroyed when the function f() ends.

there are two ways you can manage so that array remains active through out your program execution.

1) dynamically allocated arrays

//c++

int *array = new int[5];
array[0] = 1;
array[1] = 2;
array[2] = 3;
array[3] = 4;
array[4] = 5;

//c++ 11

int *array{ new int[]{ 1, 2, 3, 4, 5 } }; 

Please always remember to free dynamically allocated array using delete[] if you need to free space.

2) static array

static int array[10] = {1,2,3,4,5,6,7,8,9,10};

Static variables are variables defined using static memory allocation. for more information please see https://en.wikipedia.org/wiki/Static_variable

Upvotes: 4

Oblivion
Oblivion

Reputation: 7374

Your pointer points to array with autamtic storage. The array dies when the function returns and the pointer dangles.

The solution is not using pointer, using vector or dynamic array.

Upvotes: 8

Related Questions