Array outputs wrong variable

I'm currently learning about arrays, and tried experimenting with it in the compiler- and when I run it, it outputs the wrong variable (it's supposed to output '100', but outputs '212'- which is from a different variable). Any help would be appreciated.

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
using namespace std;
int main()
{
	int outTemp_1 = 100;
	int outTemp_2 = 32;
	int inTemp = 212;
	
	int testing[1] = {outTemp_1};
	
	cout << testing[1] << endl;
	return 0;					
}


Output terminal:
212
Hello raisetheroof00,

Lines 9 and 11 refer to an array, but where did you define the array before you used it?

I think what you are wanting is:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>

using namespace std;

int main()
{
	int outTemp_1 = 100;
	int outTemp_2 = 32;
	int inTemp = 212;
	
	int testing[1] = {outTemp_1};  // <--- (1) defines the size of the array.
	
	cout << testing[0] << endl;  // <--- (0) is the first and only element of the array.
	
	return 0;					
}

Line 11 defines an array with a of size of 1.

On line 13 when you say testing[1] this is one past the end of the array because the array starts at element (0) zero not (1).

Making this one change on line 13 the output is:

100



Andy
@Andy

Oh no, I forgot that arrays started at 0 and not 1. Silly mistake.

Thank you!

Will be taking this question down soon.
Hello raisetheroof00,

Do not remove the post. Others can learn from it.

Andy
Topic archived. No new replies allowed.