Array Problem

Hello guys, why does this code not print sword? I thought that arrays start counting at 0, that's why I did not increment numberOfItems for the first element.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
 const int MAX_ITEMS = 10;
	std::string items[MAX_ITEMS];
	int numberOfItems = 0;
	items[numberOfItems] = "sword";
	items[numberOfItems++] = "armor";
	items[numberOfItems++] = "shield";

	std::cout << "Your current items:  \n\n";
	for (int x = 0; x < numberOfItems; x++)
	{
		std::cout << items[x] << "\n";
	}
	std::cout << "\n\n";
	system("PAUSE");
	return 0;
change

1
2
3
items[numberOfItems] = "sword";
	items[numberOfItems++] = "armor";
	items[numberOfItems++] = "shield";


to

1
2
3
items[numberOfItems++] = "sword";
	items[numberOfItems++] = "armor";
	items[numberOfItems++] = "shield";


you are overwriting the [0] index because you did not increment it.
Instead of this:
1
2
3
items[numberOfItems] = "sword";
items[numberOfItems++] = "armor";
items[numberOfItems++] = "shield";


Do this:
1
2
3
items[numberOfItems] = "sword";
items[++numberOfItems] = "armor";
items[++numberOfItems] = "shield";


The way you are doing it causes the element of the array to be incremented after you have assigned it the value. So essentially you are saying:
items[0] = "sword"
items[0] = "armor"
items[1] = "shield"

Incrementing it first should fix the problem.

EDIT:
To specifically answer your question, you don't print sword because you are overwriting "sword", with "armor" in the zero element.
Last edited on
Topic archived. No new replies allowed.