Pointer stepping loop points to number outside array.

The pointer loop that I made does not stay inside the loop when looking for the lowest number. The loop still points to the correct highest number though. The number I get for the lowest is usually something like 1.07374e+08.

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
49
50
51
52
53
54
55
 #include "stdafx.h"
#include "iostream"

using namespace std;


int main()
{
	const int MAXTEMPS = 10;
	float temp[MAXTEMPS];
	float sumt = 0.0;
	float avgt = 0.0;
	float * pCur = &temp[0];
	float * pHigh = &temp[0];
	float * pLow = &temp[0];

	cout << "Please enter the ten temperatures." << endl;

	for (int i = 0; i < MAXTEMPS; i++)
	{
		cin >> temp[i];
		sumt += temp[i];
	}

	pCur = temp;
	pLow = temp;
	pHigh = temp;

	for (int i = 0; i <= sizeof(temp); i++)
	{
		
		pCur++;

		if (*pCur > *pHigh)
		{
			pHigh = pCur;
		}

		if (*pCur < *pLow)
		{
			pLow = pCur;
		}


	}
	
	avgt = sumt / MAXTEMPS;
	cout << "The lowest temperature is: " << *pLow << endl;
	cout << "The highest temperature is: " << *pHigh << endl;
	cout << "The average temperature is: " << avgt << endl;

	system("pause");

    return 0;
}
sizeof(temp) gives you the size of temp in bytes which is probably 40 (MAXTEMPS * sizeof(float)).
I changed sizeof(temp) to 10 instead and the same string of numbers came back up. I don't understand what is causing the problem.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
for (int i = 0; i <= 10; i++)
	{
		pCur++;

		if (*pCur > *pHigh)
		{
			pHigh = pCur;
		}

		if (*pCur < *pLow)
		{
			pLow = pCur;
		}

	}
Look at this snippet:
for (int i = 0; i <= 10; i++)
Now remember that arrays start at zero and stop at size - 1, not size.

Also is there a reason you're using pointer notation instead of array notation?

Last edited on
The assignment calls for me to use pointers to find the highest and lowest values in the array.OH, I understand what you said about the array size and used that to fix the program. A million thanks.
Topic archived. No new replies allowed.