Jump to content
  • Advertisement
Sign in to follow this  

accessing a 1d array, referencing as a 3d

This topic is 4516 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

I have a 1 dimensional array and I need to be accessing it as a 3 dimensional array. Here's what I've got so far:
 * Return the pointer to a particular BlockSpace object contained in the 3d play area,
 * which is stored in a 1 dimensional array.
 * \param x The index of the horizontal position
 * \param y The index of the vertical position
 * \param z The index of the depth position
BlockSpace*& getBlockPtrRef(unsigned int x, unsigned int y, unsigned int z)
	// check if we have a valid position
	if( x >= m_areaWidth || y >= m_areaHeight || z >= m_areaDepth ){
		std::ostringstream sstr;
		sstr << "BlockArea::getBlockRef: Error: tried to access block (" << x << ", " << y << ", " << z <<
				") with play area of size (" << m_areaWidth << ", " << m_areaHeight << ", " << m_areaDepth << ")";
		// log the error message to the debug console
		m_debugConsole->log( sstr.str() );

	return m_playArea[ (x*m_areaWidth*m_areaHeight) + (y*m_areaHeight) + z ];

This method was working fine when it was a 2x2x2 grid, but it needs to be easily resizeable and I just changed it to a 3x2x2 and it stuffed up, by not accessing elements 4,5,10,11 of the array, which means that it was duplicating some accesses. What am I missing? Is it something really simple, right in front of my face?

Share this post

Link to post
Share on other sites
Assuming it's laid out in memory by layers, then by rows...

int width, height, depth;

int x, y, z;

int index = (z * width * height) + (y * width) + x;

Your code should work if you replaced y*m_areaHeight with y*m_areaWidth; however, think a bit about which way of laying out the coordinates is more logical for you. As long as you always look it up the same way, you should be okay.

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.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!