Why does this happens?

I put a int into a int array and the value changes.... why? how can i fix this?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
  #include <iostream>

using namespace std;

int main(){
        int i = 32;
        int l[3];

        int z=0;
        l[z] = i;

        for(int j=0;j<3;j++){cout << l[j];}
}


This is the output:

 
32327670
The program is doing exactly what you're telling it to.

You have an integer array with three elements.

You assign thirty-two to the first (index: zero) element.

You then access each element (the last two of which haven't been initialized, that's very bad) by printing them.

You're not printing any whitespace characters such as spaces, tabs or newlines. Anyone looking at the output of your program would assume they're looking at a single, large number.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>

int main() {

	const int num_integers = 3;
	//Avoid magic numbers.

	int integers[num_integers] = {32, 64, 128};
	//Initialize all members.
	//Obviously, this can also be done by assigning a value to each element individually.

	for (int i = 0; i < num_integers; ++i) {
		std::cout << integers[i] << std::endl;
		//Make the output legible.
	}

	return 0;
}
Last edited on
Topic archived. No new replies allowed.