Printing an array

Hello all,

I have a function that returns a pointer to an array, but its elements are not being printed as I expected.
Function fills up an array from user input and prints them (correctly!) in the console. After that I use the pointer to the same array that previous function returned, and I get some result like this:

1
2
3
4
5
i=0 4
i=1 191141335
i=2 0
i=3 0
i=4 4716956


Here is my code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
int* readArrayFromUserInput(int length){
	int *pArr;
	int arr[10];
	cout << "please enter array elements\n";
	for(int i = 0; i<length; i++){
		cin >> arr[i];
	}
	cout << "reading finished\n";
	
	pArr = arr;
	for(int i = 0; i < length; i++){
		cout << "i=" << i << " " << pArr[i] << endl;
	}
	return pArr;
}

void main(){
	int length = 5;
	int* pAtr = readArrayFromUserInput(length);
	for(int i = 0; i < length; i++){
		cout << "i=" << i << " " << pAtr[i] << endl;
	}
}


What am I missing? I'm a total begginer at c++, any help will be appreciated :)
The code has undefined behaviour because you are trying to access a local array after exiting from its scope.
You are returning a pointer to a local object. But that local object ceases to exist when the function terminates. The program/operating system is free to re-use that memory for some other purpose. Hence it may be overwritten with other data.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
int* readArrayFromUserInput(int length){
    int *pArr;
    int * arr = new int[length];
    cout << "please enter array elements\n";
    for(int i = 0; i<length; i++){
        cin >> arr[i];
    }
    cout << "reading finished\n";

    pArr = arr;
    for(int i = 0; i < length; i++){
        cout << "i=" << i << " " << pArr[i] << endl;
    }
    return pArr;
}

int main(){
    int length = 5;
    int* pAtr = readArrayFromUserInput(length);
    for(int i = 0; i < length; i++){
        cout << "i=" << i << " " << pAtr[i] << endl;
    }
    delete [] pAtr;
}


you could use new [] and delete [] as above.
Last edited on
Yes I missed that part, now it works. I suppose I can just initialize a new array and pass a reference to it as an input parameter.

Thank you!
Topic archived. No new replies allowed.