Jump to content
  • Advertisement
Sign in to follow this  
Kchaa

Initializing a Multi-Dimensional Array

This topic is 4157 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hello, I am currently trying to initialize a multi-dimensional array using a for loop but I can't quite figure it out. My array declaration is:
int gameBoard[2][2];
And my initialization loop is:
for(int r = 0; r < 2; r++)
	for(int c = 0; c < 2; c++)
		gameBoard[r][c] = 0;
This doesn't seem to reach all of the elements in the array. Changing the code from
for(int r = 0; r < 2; r++)
	for(int c = 0; c < 2; c++)
to
for(int r = 0; r < 3; r++)
	for(int c = 0; c < 3; c++)
results in a run-time error, I think it's writing outside the array. Any thoughts? I'm not too good with arrays yet.

Share this post


Link to post
Share on other sites
Advertisement
I figured it out. My declaration was the problem, silly mistake. The declaration needed to be
int gameBoard[3][3];
I wanted a 9 square board (Tic Tac Toe) and was giving myself a 4 square board.

Share this post


Link to post
Share on other sites
It's very simple. The number you put for the dimension is the size in that direction. The elements are numbered starting from zero, up to but not including the size (hence strict less-than). This gives exactly the right amount of numbers: for example, 5 elements are numbered 0, 1, 2, 3, 4 - that is, 5 numbers, which start from 0 and range up to but not including 5.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!