Problem with pointer

Hello,

When the program goes to MinMax function(line 19), the value of the array changed automatically, why?

Thanks

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#include <iostream>
#include <stdlib.h>    
#include <time.h>
using namespace std;

int* FillArray()
{
	int arr[100];
	srand(time(NULL));
	for (int i = 0; i < 100; i++)
	{
		arr[i] = rand()%500;
	}
	return arr;
}

void MinMax(int* arr)
{
// Here! changed value of array! why?
	int maxIndex = 0;
	int minIndex = 0;
	int max = arr[0];
	int min = arr[0];

	for (int i = 1; i < 100; i++)
	{
		if (arr[i] < min)
		{
			min = arr[i];
			minIndex = i;
		}
		if (arr[i] > max)
		{
			max = arr[i];
			maxIndex = i;
		}
	}
	cout << "Min: " << min << "\t" << "Max: " << max << endl;
	cout << "Min Index:  " << minIndex << "\t" << "Max Index: " << maxIndex << endl;
}

int main()
{
	int* arr = FillArray();
	MinMax(arr);

	return 0;
}
Last edited on
I don't know what you are seeing but fillarray is wrong. It returns the address of a local object that is deleted after that function ends. That data was on the stack, and the stack changes all the time, so likely it looks as if the array's data changed, but in reality, its undefined behavior due to a bad pointer and anything could happen.
If you want to ensure that arr is unchanged in MinMax(), declare it const. As in:
 
void MinMax(const int* arr)


However, that's not your problem.

This is:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
int main() {
    int* arr = FillArray();  // where does arr live, if we're returning a pointer to it?
    MinMax(arr);
}

int* FillArray()
{
    int arr[100]; // create a local array on the stack
    // do stuff with it
    return arr; // return a pointer to my array on the stack

    // when we return, the memory under the stack is reused
    // we have a pointer to junk
}


Always, with pointers, we need to know what we're pointing to.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
void FillArray(int* arr, std::size_t size) {
    for (std::size_t i = 0; i != size; ++i)
        arr[i] = rand()%500;
}

void MinMax(const int* arr, std::size_t size) {
    int maxIndex = 0;
    int minIndex = 0;
    int max = arr[0];
    int min = arr[0];

    for (std::size_t i = 0; i != size; ++i) {
        if (arr[i] < min) {
            min = arr[i];
            minIndex = i;
        }
        if (arr[i] > max) {
            max = arr[i];
            maxIndex = i;
        }
    }

    std::cout << "Min: " << min << "\t" << "Max: " << max << '\n';
    std::cout << "Min Index:  " << minIndex << "\t" << "Max Index: " << maxIndex << '\n';
}

int main() {
    srand(time(NULL));

    constexpr std::size_t arrSize = 100;
    int arr[arrSize];
    FillArray(arr, arrSize);
    MinMax(arr, arrSize);
}
Last edited on
Thank you so much.
Topic archived. No new replies allowed.